加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过回调函数获取AJAX的responseText

发布时间:2020-12-16 01:28:46 所属栏目:百科 来源:网络整理
导读:项目需求: 我在url1中解析responseText,获得jsonObj,判断里面data[0]==1,如果成立,那么要去URL2里去拿另一个数据。然后对数据进行处理。 var xhr = getXhr(); xhr.open("get",url1); xhr.send(null); xhr.onreadystatechange = function () { if (xhr.stat

项目需求:

我在url1中解析responseText,获得jsonObj,判断里面data[0]==1,如果成立,那么要去URL2里去拿另一个数据。然后对数据进行处理。

var xhr = getXhr();
    xhr.open("get",url1);
    xhr.send(null);
    xhr.onreadystatechange = function () {
        if (xhr.status == 200 && xhr.readyState == 4) {
            var jsonObj = JSON.parse(xhr.responseText);
if(jsonObj.data[0]==1){
var aa=getOther();//另一个AJAX请求。
console.log(aa);
}
        }
    }
}

但是,另一个AJAX请求返回不了responseText。

function getOther(){
    var chapterXhr = getXhr(),data;
    chapterXhr.open("get",url2,true);
    chapterXhr.send(null);
    chapterXhr.onreadystatechange = function () {
        if (chapterXhr.status == 200 && chapterXhr.readyState == 4) {
            data=JSON.parse(chapterXhr.responseText);
        }
    };
return data;//返回打印是undefined
}

之前用的办法是定义一个参数STR,外围还有一个函数包裹着这两个函数的函数,通过定义参数的方式,操作responseText值。

function getOther(str) {
    if (str != undefined) {
        str = '';
    }
    var chapterXhr = getXhr(),data;
 chapterXhr.open("get",true); 
chapterXhr.send(null);
chapterXhr.onreadystatechange = function () { 
if (chapterXhr.status == 200 && chapterXhr.readyState == 4) { 
               str =JSON.parse(chapterXhr.responseText); } };
         }     
        }
    };

但是新的需求这样不能做。所有学习了个新技能。

var xhr = getXhr();
    xhr.open("get",url1);
    xhr.send(null);
    xhr.onreadystatechange = function () {
        if (xhr.status == 200 && xhr.readyState == 4) {
            var jsonObj = JSON.parse(xhr.responseText);
if(jsonObj.data[0]==1){
     otherAJAX(function(data){
                       console.log(data);
                   });
}
        }
    }
}
 function otherAJAX(callback){
        var chapterXhr = getXhr();
        chapterXhr.open("get",url2);
        chapterXhr.send(null);
        chapterXhr.onreadystatechange = function () {
            if (chapterXhr.status == 200 && chapterXhr.readyState == 4) {
                callback(JSON.parse(chapterXhr.responseText));//输出为正确的报文

            }
        };
    }

我是一个水前端,简称水端....

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读