/**
* @description: ajax封装
* @param {string} //post or get or others请求方式
* @param {url} //url地址
* @param {any} 参数
* @param {function} 回调函数
* @return {type}
*/
function Myajax(method,url,params,callback) {
var xhr;
//建立连接
//兼容处理
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//get方式参数放在url地址中也就是params
if (method.toLowerCase() == 'get') {
url += '?' + params;
}
//打开链接
xhr.open(method, url);
//状态改变时的处理,多为DOM操作
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
//当请求方式为post时传参方式有所不同参数放在send()中也就是发送请求时
if (method.toLowerCase() == 'post') {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//post方式发送请求
xhr.send(params);
} else {
//get方式发送请求
xhr.send(null);
}
}
ajax封装
最新推荐文章于 2024-07-09 18:13:44 发布