封装ajax

作者: LiLi原上草 | 来源:发表于2017-05-01 23:21 被阅读40次


为了方便大家阅读,直接截图上传,后面附有代码,可以复制粘贴:

// 参数情况

// method,url,data

function ajax(method, url, data, callback) {

// 1、创建请求对象

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

// 2、配置请求参数并发送请求

method = method.toUpperCase();

if (method == 'GET') {

xhr.open('GET', url + '?' + data, true);

xhr.send(null);

} else if (method == 'POST') {

xhr.open('POST', url, true);

xhr.send(data);

} else {

console.error('请传入合法的请求方式');

}

// 3、监听状态

xhr.onreadystatechange = function () {

if (xhr.readyState == 4 && xhr.status == 200) {

// 向外返回服务器的数据

// 根据responseXML属性的是是否为空推断出数据格式

// xhr.resopnseXML为null,表示请求的是json数据,否则,请求的是xml数据

if (!xhr.responseXML) {

callback(xhr.responseText);

} else {

callback(xhr.responseXML);

}

}

}

}

相关文章

网友评论

    本文标题:封装ajax

    本文链接:https://www.haomeiwen.com/subject/ilwqtxtx.html