ajax.js 代码如下:
(function(){
var ajax = {
getxhr:function(){
return new XMLHttpRequest();
},
get:function(path,sync = true,fun){
var xhr = this.getxhr();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
fun(xhr.responseText);
}
}
xhr.open("get",path,sync);
xhr.send();
},
post:function(path,post_data,sync = true,fun){
var xhr = this.getxhr(path,sync = true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
fun(xhr.responseText);
}
}
xhr.open("post",path,sync);
xhr.send(post_data);
}
}
//防止对象名字 于其他插件重复
window.jixing = ajax;
})()
如何使用:
<!-- 引入 ajax.js文件 -->
<script src="./ajax.js"></script>
<script>
var txt = document.getElementById("txt");
txt.onblur = function(){
var xhr = window.jixing.getxhr();
window.jixing.get("http://127.0.0.1:8080/",true,function(data){
alert(data);
});
}
</script>