ITPub博客

首页 > IT职业 > IT生活 > ajax原理笔记

ajax原理笔记

IT生活 作者:tomorrowcome 时间:2021-09-09 09:55:26 0 删除 编辑

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


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/875/viewspace-2814463/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: jQuery中的DOM操作
请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    122
  • 访问量
    928