原生 JavaScript 封住 ajax
var loadData = function (obj) {
"use strict";
// obj is null
var obj = obj || {};
var type, url, success, error, data, result;
type = obj.type || "post";
url = obj.url || "";
success = obj.success || "";
error = obj.error || ""
data = obj.data || "";
var toStr = Object.prototype.toString;
// 1. 创建 XMLHttpRequest object
var xhr = new XMLHttpRequest();
// 判断数据是否合法
var data_type = toStr.call(data);
switch (data_type) {
case "[object Object]":
case "[object FormData]":
break;
default:
result = "不合法的数据";
return typeof(error) === 'function' && error(result);
}
// 2. 准备发送 并且 执行发送
if (type === "get") {
var arr = [];
for (var i in data) {
arr.push(i + "=" + data[i]);
}
data = arr.join("&");
url += "?" + data;
xhr.open(type, url, true);
xhr.send(null);
}else if (type === "post") {
data = JSON.stringify(data);
xhr.open(type, url, true);
xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
xhr.send(data);
}
// 3. 设置回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
switch (xhr.status) {
case 200:
result = JSON.parse(xhr.responseText);
return typeof(success) === "function" && success(result);
case 404:
result = "404 no request resources found";
return typeof(error) === "function" && error(result);
case 500:
result = "500 server error !"
return typeof(error) === "function" && error(result);
default :
result = "未知错误";
return typeof(error) === "function" && error(result);
}
}
}
}
调用
loadData({
type: "post",
// url: "http://ajax.web.com/api/index/get_all_art",
url: "http://ajax.web.com/api/admin/login",
success: function (result) {
console.log(result);
},
error: function (result) {
console.log(result)
},
data: {
"username": 'dsasad',
"passwd": 'dasd..'
}
});