发布作者: MengZe2
最后更新: 2024年 06月 13日 13:14
作品采用: 《 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 》许可协议授权
这段代码有近10年历史了,猜猜我从哪搞来的
function ajax(options) {
var xhr = null;
var type = 'GET';
var params = formsParams(options.data);
if(typeof options.type != 'undefined'){
type = options.type.toUpperCase();
}
//创建对象
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (typeof options.async == "undefined") {
options.async = true;
}
// 处理请求成功的回调函数
xhr.onload = function(){
if (xhr.status >= 200 && xhr.status < 300) {
if (typeof options.datatype == "undefined" || options.datatype == "json") {
if(typeof options.success === 'function'){
options.success(JSON.parse(xhr.responseText));
}
} else {
if(typeof options.success === 'function'){
options.success(xhr.responseText);
}
}
} else {
if(typeof options.error === 'function'){
options.error(xhr.statusText);
}
}
}
// 处理请求错误的回调函数
xhr.onerror = function() {
if(typeof options.error === 'function'){
options.error(xhr.statusText);
}
}
// 设置请求头部
if (options.headers) {
for (var header in options.headers) {
xhr.setRequestHeader(header, options.headers[header]);
}
}
// 设置请求方法、URL、是否异步、发送请求
if (type == "GET") {
xhr.open(type, options.url + "?" + params, options.async);
xhr.send(null);
} else if (type == "POST") {
xhr.open(type, options.url, options.async);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
function formsParams(data) {
var arr = [];
for (var prop in data) {
arr.push(prop + "=" + data[prop]);
}
return arr.join("&");
}
}
// 使用
ajax({
url: "api.php",// 请求地址
type: "POST",// 请求方式
async: true,// 同步:false,异步:true,默认为true
datatype: "json",// 返回数据的格式,"json","text",默认为json
headers: {},// 设置请求头部,{"token": "123456"}
data: {// post数据
code: "s2sdd",
link: location.href
},
success: function (res) {// 处理请求成功
console.log(res);
},
error: function (res) {// 处理请求错误
console.log(res);
}
})
说的真好
好
说的好, 非常好
曹曹博主,练练实战