var Ajax = {
get(url, data, callback) {
var querystring = "";
for (var i in data) {
querystring += i + "=" + data[i] + "&";
}
querystring = querystring.slice(0, -1);
// 1 初始化xhr
var xhr = new XMLHttpRequest();
// 2 监听状态
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var obj = JSON.parse(xhr.responseText);
callback(obj);
}
}
// 3 open
xhr.open("get" , url + "?" + querystring, true);
// 4 send
xhr.send();
},
post(url, data, callback) {
var querystring = "";
for (var i in data) {
querystring += i + "=" + data[i] + "&";
}
querystring = querystring.slice(0, -1);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.open("post" , url, true);
// 将请求头内容更改 改为表单的内容类型
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8")
xhr.send(querystring);
},
jsonp(url, data, callback) {
var querystring = '';
for (var i in data) {
querystring += i + "=" + data[i] + "&";
}
querystring = querystring.slice(0, -1);
// 1 创建script标签
var script = document.createElement('script');
// 2 设置script的src
script.src = url + "?" + querystring;
// 3 script只有在树上的时候才会发送请求
document.body.appendChild(script);
// 4 将callback作为回调函数 注册到全局
window[data.callbackName] = callback;
}
}
封装ajax
最新推荐文章于 2024-05-03 14:31:55 发布