注意一下火狐,360IE78下的坑:
返回过来的response在不同浏览器下的字符串不一致
// response(chrome):<pre style="word-wrap: break-word; white-space: pre-wrap;">{"success":true,"info":"保存成功!","PhotoURL":"/upload_BenefitsFund/33/20151204102733907401WRME4.png"}</pre>
// response(360IE78):<PRE>{"success":true,"info":"保存成功!","PhotoURL":"/upload_BenefitsFund/33/20151204101939484PTND5ELI.png"}</PRE>
// response(Firefox):"<pre>{"success":true,"info":"保存成功!","PhotoURL":"/upload_BenefitsFund/33/20151204102931978J0GLUULI.png"}</pre>"
单纯的正则匹配并移除多余部分已经不能满足不同浏览器下的需求了
于是我们只能通过”{” ,”}”匹配截取”{”前面与”}”后面的
最后把剩余部分的json格式字符串再通过eval转为json
var UploadImg = function ($_selector, applyType, type) { var button = $($_selector), interval; new AjaxUpload(button, { action: 'Handler/Users/BenefitsFund.ashx?action=ImgSave&applyType=' + applyType + '&type='+type, name: 'myfile', // dataType: "json", onSubmit: function (file, ext) { if (!(ext && /^(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$/.test(ext))) { alert("图片格式不正确,请重新选择!"); return false; } }, onComplete: function (file, response) {//当上传完成时的操作 console.log(response); // response(chrome):<pre style="word-wrap: break-word; white-space: pre-wrap;">{"success":true,"info":"保存成功!","PhotoURL":"/upload_BenefitsFund/33/20151204102733907401WRME4.png"}</pre> // response(360IE78):<PRE>{"success":true,"info":"保存成功!","PhotoURL":"/upload_BenefitsFund/33/20151204101939484PTND5ELI.png"}</PRE> // response(Firefox):"<pre>{"success":true,"info":"保存成功!","PhotoURL":"/upload_BenefitsFund/33/20151204102931978J0GLUULI.png"}</pre>" response = response.substring(response.lastIndexOf("{"));///去response中"{"前面的除字符串 // console.log(response); response = response.substring(0, response.lastIndexOf("}") + 1);///去response中"}"后面的除字符串 //alert(response); // console.log(response); //var reg = /<pre.+?>(.+)</pre>/g; //var result = response.match(reg); //response = RegExp.$1;//去除多余的字符串 // alert(response) //response = JSON.parse(response);//转成json格式 IE78不支持 // response = $.parseJSON(response);//转成json格式 response = eval("(" + response + ")");//转成json格式 IE78支持 // response = JSON.parse(response); //alert(response) // console.log(response); //var _MyJson = '{ "success": true, "info": "保存成功!", "PhotoURL": "/upload_BenefitsFund/33/201512031628303370LTKBULS.png" }'; //alert(_MyJson); //console.log("1" + _MyJson); //_MyJson = eval("(" + _MyJson + ")"); // alert(response.success) if (response.success == true) { alert("上传成功"); button.find(".upload_img").attr("src", response.PhotoURL) } else { alert(response.reason); } //if (file!= "") { // //window.location.href = window.location.href; // alert("dd"); // //alert(response) // console.log(response) //} }, onError: function (id, fName, error) { ZENG.msgbox.show("上传失败,请重试!", 1, 2000); window.clearInterval(interval); } }); } new UploadImg(".Js_upload_sfz01",4,0);//上传身份证正面