<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/*
自定义AJAX
当data传送文件时 contentType 需设置 false (不需要头部申明)
ajax(访问地址,{
type: "post",
data:{
id: 123
},
contentType: false,
success: function(data){
console.log(data);
},
error: function(){}
});
*/
function ajax(url, options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "JSON";
var params = formatParams(options.data);
function formatParams(obj) {
var isJson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" &&
!obj.length;
if (isJson) {
var arr = [];
for (var name in obj) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(obj[name]));
}
arr.push(("v=" + Math.random()).replace(".", "a").replace("1", "b").replace("3", "c").replace("5", "d").replace(
"7", "e").replace("9", "k"));
return arr.join("&");
} else {
return obj;
}
}
var xhr;
if (win.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (win.ActiveXObject("Microsoft.XMLHTTP")) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
if (options.type == "GET") {
xhr.open("GET", url + "?" + params, true);
xhr.send(null);
} else if (options.type == "POST") {
xhr.open("POST", url, true);
if (!options.contentType && options.contentType != false) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
}
xhr.send(params);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300 || status == 304) {
typeof xhr.responseText === "string" && options.success && options.success(eval('(' + xhr.responseText + ')'),
xhr.responseXML);
} else {
options.error && options.error(status);
};
}
};
}
</script>
</body>
</html>
自定义AJAX
最新推荐文章于 2022-08-31 12:29:18 发布