原生 JS Ajax
2018-10-23 本文已影响0人
hgzzz
//封装Ajax
function ajax(obj) {
// 1. 获取异步对象
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
var xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. 转换 url 和 参数数据格式
obj.url = obj.url + '?rand=' + Math.random();
obj.data = params(obj.data);
// get 请求需要在 url 后面拼接 查询参数
if (obj.method === 'get') {
obj.url = obj.url.indexOf('?') == -1 ? obj.url + '?' + obj.data : obj.url + '& ' + obj.data;
}
if (obj.async === true) {
// 4. 提前绑定监听事件
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
if (xhr.status == 200){
obj.success(xhr.responseText);
}else{
alert('获取数据错误! 错误代号' + xhr.status +',错误信息' + xhr.statusText);
}
}
};
}
// 3. 设置请求方式、请求地址和异步
xhr.open(obj.method,obj.url,obj.async);
// 3.1 如果是 post 请求,就要在 send() 中传入数据
if (obj.method === 'post'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(obj.data);
}else{
// 3.2 get 请求则不需要发送数据,查询数据在 url中
xhr.send(null);
}
if (obj.async === false) {
if (xhr.status == 200){
obj.success(xhr.responseText);
}else{
alert('获取数据错误! 错误代号' + xhr.status +',错误信息' + xhr.statusText);
}
}
}
//调用ajax
window.addEventListener('click',function () {
ajax({
method: 'get',
url: 'Ajax.php',
data: {
'name' : 'zhangsan',
'age' : 20
},
success: function (text) {
console.log(decodeURIComponent(text));
},
async:true
})
},false);
//名值对转化成字符串
function params(data) {
var arr = [];
for (var i in data){
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return (arr.join('&'));
}