问题描述
下面的例子是一个Ajax的post请求的代码,这段代码在测试运行的时候,发现返回的状态码为400,服务器不能理解的请求,后来经过查看和修改,发现只需要将下面的代码稍微改造一下就好了
原代码
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)); }