jquery - 如何使用通过 jQuery.get 调用获得的 URL 来执行另一个调用?
问题描述
基本上,我想做的是:
var mydata = null;
jQuery.get(ANOTHER_URL, function(data) {
mydata = data;
}).then(jQuery.get(parsingFunction(mydata), function(otherData) {/*do stuff with otherData*/}));
parsingFunction(notYetAnURL) {
/*does stuff with notYetAnUrl*/
return nowIsURL;
}
问题是..这不起作用。当第二个 jQuery.get 调用发生时,mydata
似乎仍然是null
. 我是 Ajax 和一般异步编程的新手,所以如果这个问题看起来很愚蠢,我深表歉意,但我真的无法摆脱这个问题。有人可以帮忙吗?
解决方案
您没有为结果使用回调函数。因此,最好使用回调函数.done
和.fail
功能,以获得更好的可读性和错误捕获。
function firstService(){
jQuery.get(ANOTHER_URL)
.done(function(data){
// first result
if(data){
secondService(data);
}
})
.fail(function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.error(error);
});
}
function secondService(newData){
jQuery.get(getSecondServiceUrlFromData(newData))
.done(function(data){
// second result
})
.fail(function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.error(error);
});
}
function getSecondServiceUrlFromData(data) {
/*does stuff with notYetAnUrl*/
return nowIsURL;
}
firstService();
推荐阅读
- oracle - 当数据出现在双引号中时,使用 SQL 加载器将数据从 CSV 文件(由管道“|”分隔的数据)加载到表中
- github - 如何在 github 板上添加问题
- haskell - 奇怪的波浪号语法
- c# - 将浏览器控件另存为图像
- visual-studio-2017 - 在 Visual Studio 2017 中发布 asp.net 核心 webapi 项目时转换 web.config
- java - sendRedirect 与转发到根路径
- c++ - 使用 SimplicialCholesky Eigen 求解大型稀疏线性系统
- javascript - chart.js - 工具提示回调函数在取消选择图例时忽略隐藏的数据集
- text-to-speech - Linux 中的离线波兰语 TextToSpeech
- sql - 计算每个月的实际工作日