原生ajax封装
function $ajax(obj) {
var type = obj.type || "GET";
var url = obj.url;
var data = url.data;
var query = "";
for (let key in data) {
query += `${key}=${data[key]}&`
}
query = query.substr(0, query.length - 1)
if (type.toUpperCase == "GET") {
var xhr = new XMLHttpRequest();
xhr.open(type, url + "?" + query, true);
xhr.send()
} else {
var xhr = new XMLHttpRequest();
xhr.open(type, url + query, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(query)
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
let resObj = JSON.parse(xhr.responseText)
obj.success(resObj);
}
}
}
实例调用
$.ajax({
type: "get/post",
url: "http://localhost:3000/add",
data: {
"name": "sun",
"age": 18
},
success: function(res) {
console.log(res);
}
});