封装请求
function httpRequest(obj, successfun, errFun) {
var xmlHttp = null;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest;
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) {
alert("浏览器不支持xmlHttp");
return;
}
var httpMethod = (obj.method || "Get").toUpperCase();
var httpDataType = obj.dataType || 'json';
var httpUrl = obj.url || '';
var async = true;
if (httpMethod == "POST") {
requestData = JSON.stringify(obj.data)
console.log(requestData);
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
successfun(xmlHttp.responseText);
} else {
errFun;
}
}
}
if (httpMethod == 'GET') {
xmlHttp.open("GET", httpUrl, async);
xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlHttp.send(null);
} else if (httpMethod == "POST") {
xmlHttp.open("POST", httpUrl, async);
xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlHttp.send(requestData);
}
}
执行请求
httpRequest({
method: "post",
url: "https://jstest.91betterwei.com/burypoint-api/save",
data: {
applicationId: "1",
type: "1",
},
dataType: "json"
}, function (res) {
console.log(res)
}, function () {
console.log("请求失败");
});