function AJAX() { var xhr = null; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { try{ xhr = new ActiveXObject('Microsoft.XMLHttp'); }catch(e){ xhr = new ActiveXObject('msxml2.xmlhttp'); } } //get请求 this.get = function(url,success,fail){ xhr.open("GET", url,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4) { if(xhr.status==200) { var txt = xhr.responseText; txt = JSON.parse(txt); success(txt); } else { if(fail) { fail(xhr.status); } } } }; xhr.send(null); }; //post请求 this.post = function (url,param,success,fail) { xhr.open("POST", url,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4) { if(xhr.status==200) { var txt = xhr.responseText; txt = JSON.parse(txt); success(txt); } else { if(fail) { fail(xhr.status); } } } }; xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(param); }; }//使用var ajax = new AJAX(); ajax.get("test.json",function(data){ //成功回调},function(data){//失败回调});
作者:一枚程序猿
链接:https://www.jianshu.com/p/83c4f3341bb1
共同学习,写下你的评论
评论加载中...
作者其他优质文章