原生ajax封装

function ajax(method,url,data,dispatch){
if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else if (window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
xmlHttp.open(method,url,true);

xmlHttp.setRequestHeader("Content-Type","application/json");
//xmlHttp.setRequestHeader("charset","utf-8");
xmlHttp.send(decodeURI(data));
if(method.toLowerCase()=='get'){
xmlHttp.onreadystatechange=callback;
}else if(method.toLowerCase()=='post'){
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4) { //判断对象的状态是否交互完成
if (xmlHttp.status == 200) { //判断http的交互是否成功,200表示成功
console.log(xmlHttp.responseText);
//回调传递参数
let json = JSON.parse(xmlHttp.responseText);
json.id = searchPlanObj.apId; //将点击那行的id传到reducers里对应的方法里
if ( json["message"] == "success" ) {
dispatch(receiveAssetPackInfo( json));
}
else {
message.error(json['message']);
}
} else {
alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);
}
}
};
}

}
posted @ 2016-10-13 16:00  小小公举  阅读(141)  评论(0编辑  收藏  举报