悠悠楠杉
网站页面
function ajax(options) {
var xhr = null;
var params = formsParams(options.data);
//创建对象
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (typeof options.async == 'undefined') {
options.async = true;
}
// 连接
if (options.type.toLowerCase() == "get") {
xhr.open(options.type, options.url + "?" + params, options.async);
xhr.send(null)
} else if (options.type.toLowerCase() == "post") {
xhr.open(options.type, options.url, options.async);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
if (options.async) {
xhr.onreadystatechange = function () {
optionsSuccess();
}
} else {
optionsSuccess();
}
function optionsSuccess(){
if (xhr.readyState == 4 && xhr.status == 200) {
if (typeof options.datatype == 'undefined' || options.datatype == 'json') {
options.success(JSON.parse(xhr.responseText));
} else {
options.success(xhr.responseText);
}
}
}
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
data: {// post数据
code: "s2sdd",
link: location.href
},
success: function (res) {// 返回数据
console.log(res);
}
})