gpt4 book ai didi

javascript - 如何在一个主函数中使用两次 getJSON 调用?

转载 作者:行者123 更新时间:2023-11-30 15:01:58 25 4
gpt4 key购买 nike

我当前的 <body>...<script>....</script></body>选项卡具有此流程:

<script>

$(document).ready(function(){
function main(){

var urlOne = 'https:....';
var summaryTable = {};
var distinctKeys = [];
$.getJSON(urlOne, function(jsonOne) {
// write code to collect data from urlOne and put it in 'summaryTable' AND 'distinctKeys'
distinctKeys.append(jsonOne['something']);
}); // end of first getJSON

/* ****** the javascript would NOT execute anything below this **** */
var foo = distinctKeys.length;
for (var i = 0; i < foo; i++) {

var curUrl = urlConstant + distinctKeys[i];
$.getJSON(curUrl, function(jsonTwo) {
// do stuff to add more info into 'summaryTable'
}); // end of second getJSON

}; // end of for loop

}; // end of main()
main();
}); // end of all javascript code
</script>

正如我上面提到的,代码不会继续执行低于 /* ****** the javascript would NOT execute anything below this **** */ 的任何内容。线。我注意到 distinctKeyssummaryTable第一次还是空的$.getJSON调用被执行。我想调用getJSON按该特定顺序进行两次——第二次是基于从第一次通话中获得/收集的信息。谁能解释一下我如何才能做到这一点?

预先感谢您的回答!

最佳答案

给你一个解决方案

var urlArray = ['https://one.com', 'https://two.com', 'https://three.com'];
var i = 0;

var getJSONData = function(){
$.getJSON(urlArray[i], function(data){
console.log(data);

i++;
if( i < urlArray.length)
getJSONData();
});

};

语法错误 var urlArray = ['https://one.com', 'https://two.com', 'https://three.com];,你缺少最后一个单引号

我建议不要将 getJSON 方法放在 for 循环 中,而是将其放在方法中并在收到来自 AJAX 调用和 for 获取 url 使用变量

根据更新的问题更新答案

$(document).ready(function(){
function main(){
var urlOne = 'https:....';
var summaryTable = {};
var distinctKeys = [];
var i = 0;
$.getJSON(urlOne, function(jsonOne) {
// write code to collect data from urlOne and put it in 'summaryTable' AND 'distinctKeys'
distinctKeys.append(jsonOne['something']);
getJSONData(); // this will be used to call for the first time.
}); // end of first getJSON

var getJSONData = function(){
var curUrl = urlConstant + distinctKeys[i];
$.getJSON(curUrl, function(data){
console.log(data);
i++;
if( i < distinctKeys.length)
getJSONData();
});
};

}; // end of main()
main();
}); // end of all javascript code

希望对您有所帮助。

关于javascript - 如何在一个主函数中使用两次 getJSON 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46397408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com