跨域formData格式的数据,X5内核bug的解决
因为在交互中,存在跨域的问题,采用了formData的数据格式给后台传参。一般浏览器都搞定了,偏偏有些浏览器不好使,作为前端程序猿,主要工作就是解决样式问题!!!找方法解决吧……
采用append方法的问题出在,X5内核浏览器只能截取到最后一个append到formData中的参数,前面所有的参数将忽略掉。
找了半天发现,可以用模拟的formData数据格式的“骗”后台。
后台需要的数据格式:

首先构造WebKitFormBoundary格式:
var makeBoundary = function() { return '----WebKitFormBoundary'+btoa(Math.random().toString()).substr(0,12); };
var boundary = makeBoundary();
接下来用ajax传输数据:
$.ajax({ url: "http://api."+ localhostname +"/authorization", method: 'post', type:"post", contentType: 'multipart/form-data; boundary='+boundary, headers: { 'Authorization': ins_id + "-" + ins_token }, processData: false, cache: false, data: '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="mobile"\r\n\r\n' + mobile + '\r\n' + '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="password"\r\n\r\n' + pwd + '\r\n' + '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="seq_no"\r\n\r\n' + seq_no + '\r\n'+ '--' + boundary + '--', beforeSend:function(){ $(".collect_popup span").html("正在认证,请耐心等待"); $(".collect_popup").css("display","block"); $("#auth_password").prop('disabled', true); $(".collect").prop('disabled', true); $(".collect").css({"background":"#999","cursor":"default","color":"white"}); }, success: function(data,textStatus){ if(textStatus == "nocontent"){ $("title").html("认证完成"); collectFinished(); }else{ console.log("Response for collect_btn authorizations :{"+"err_code:"+data.err_code+";"+"err_msg:"+data.err_msg+"}"); parseAuthorityResponse(data); $(".collect_popup").css("display","none"); return false; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log("Response for collect_btn authorizations Error:"+XMLHttpRequest+textStatus+errorThrown); $(".tips p").html("数据采集异常,请稍后重试!"); $(".tips").css("display","block"); $(".collect_popup").css("display","none"); $(".collect").prop('disabled', false); $(".collect").css({"background":"#fff","cursor":"pointer","color":"#fe9441"}); return false; } })
需要做的就是,两点:
1、contentType: 'multipart/form-data; boundary='+boundary,
2、
data: '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="mobile"\r\n\r\n' + mobile + '\r\n' + '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="password"\r\n\r\n' + pwd + '\r\n' + '--' + boundary + '\r\n'+ 'Content-Disposition: form-data; name="seq_no"\r\n\r\n' + seq_no + '\r\n'+ '--' + boundary + '--',
需要注意的是:包括“-”、“\r\n”在内的,所有格式都必须和后台要求保持一致!
好了。快去解决问题吧!
祝福新年快乐!

浙公网安备 33010602011771号