简介这篇文章主要介绍了原生js实现ajax的方法以及相关的经验技巧,文章约927字,浏览量479,点赞数2,值得参考!
var Ajax={
get: function (url,fn){
var obj=new XMLHttpRequest(); // XMLHttpRequest对象用于在后台与服务器交换数据
obj.open(‘GET‘,url,true);
obj.onreadystatechange=function(){
if (obj.readyState == 4 && obj.status == 200) { // readyState==4说明请求已完成
fn.call(this, obj.responseText); //从服务器获得数据
}
};
obj.send(); //将请求发往服务器
},
post: function (url, data, fn) {
var obj = new XMLHttpRequest();
obj.open("POST", url, true);
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 设置请求头
obj.onreadystatechange = function () {
if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) { // 304未修改
fn.call(this, obj.responseText);
}
};
obj.send(data);
}
}