您的位置:首页 > 其它

通过回调函数获取AJAX的responseText

2016-09-25 00:00 295 查看
项目需求:

我在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",url2, 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));//输出为正确的报文

}
};
}

我是一个水前端,简称水端....
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  callback