問(wèn)題描述
下面的例子是一個(gè)Ajax的post請(qǐng)求的代碼,這段代碼在測(cè)試運(yùn)行的時(shí)候,發(fā)現(xiàn)返回的狀態(tài)碼為400,服務(wù)器不能理解的請(qǐng)求,后來(lái)經(jīng)過(guò)查看和修改,發(fā)現(xiàn)只需要將下面的代碼稍微改造一下就好了
原代碼
var send = function (url, params, fn) { var me = this; var xhr = null; var data = ''; fn = fn || function() {}; params = params || {}; for(var item in params) { data += item + '=' + params[item] + '&'; } if(data[data.length - 1] == '&') { data = data.slice(0, data.length - 1); } if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else if(window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("post", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function () { if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) { fn(JSON.parse(xhr.responseText)); } }; xhr.send(JSON.stringify(params));}
修改之后的代碼
var send = function (url, params, fn) { var me = this; var xhr = null; fn = fn || function() {}; params = params || {}; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else if(window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("post", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function () { if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) { fn(JSON.parse(xhr.responseText)); } }; xhr.send(JSON.stringify(params));}
這兩段代碼的差別就是,修改之后的代碼去掉了關(guān)于data這個(gè)變量的處理以及在send中傳遞的參數(shù)變?yōu)榱藀arams這個(gè)變量
問(wèn)題解惑
問(wèn)題是解決了,但是我心里的疑問(wèn)卻產(chǎn)生了,之前在使用原生的Ajax的時(shí)候,當(dāng)method為post的時(shí)候,傳遞的參數(shù)的形式是”name=123&age=32”這樣子的,那么為什么現(xiàn)在傳遞一個(gè)序列化的JSON對(duì)象就可以了呢?
這時(shí)候我注意到自己所加的MIME類型,也就是設(shè)置Content-type的那處,我設(shè)置的是"application/json",這樣看起來(lái)就解釋的通了,這時(shí)候我回想起之前常用的MIME類型是“application/x-www-form-urlencoded”,這種時(shí)候send方法傳遞的參數(shù)就要求是”name=123&age=32”這樣子的,到這里,解惑完畢啦(~ ̄ 主站蜘蛛池模板: 修武县| 宣汉县| 永宁县| 榆社县| 三亚市| 巴东县| 邵东县| 子洲县| 晋城| 灵台县| 大连市| 双柏县| 昌黎县| 阜阳市| 阳信县| 巴中市| 通江县| 邵阳县| 烟台市| 云阳县| 比如县| 康定县| 颍上县| 叙永县| 曲松县| 黔东| 庄浪县| 吴桥县| 体育| 长乐市| 黄浦区| 梨树县| 正宁县| 长葛市| 商城县| 马关县| 辽宁省| 台中市| 海晏县| 柳河县| 东光县|