作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我当前的 <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 **** */
的任何内容。线。我注意到 distinctKeys
和 summaryTable
第一次还是空的$.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/
我是一名优秀的程序员,十分优秀!