javascript $getJSON 和 for 循环问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15347750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:29:12  来源:igfitidea点击:

$getJSON and for loop issue

javascriptmediawiki-api

提问by Onei

This is to populate a table with the amount of results that are returned from the MediaWiki API query /api.php?action=query&list=querypage&qppage=BrokenRedirects. The number of results is then added to the id, for example:

这是用从 MediaWiki API 查询返回的结果数量填充表/api.php?action=query&list=querypage&qppage=BrokenRedirects。然后将结果数添加到 id 中,例如:

// BrokenRedirects
$.getJSON('/api.php?action=query&list=querypage&qppage=BrokenRedirects&format=json', function (data) {
    $('#BrokenRedirects').text(data.query.querypage.results.length);
});

But as it's being repeated another 7 times I made the arguments for qppage into an array and used a for loop to shorten overall code.

但是当它再重复 7 次时,我将 qppage 的参数放入一个数组中,并使用 for 循环来缩短整体代码。

var array = ['BrokenRedirects',
             'DoubleRedirects',
             'Unusedcategories',
             'Unusedimages',
             'Wantedcategories',
             'Wantedfiles',
             'Wantedpages',
             'Wantedtemplates'];

for (var i = 0; i < array.length; i++) {
    $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
    });
}

The first, unlooped, version works. But when I added a loop it didn't. The $getJSONpart executes, but it then fails to add the resultant data to the id. I ran it through JSLint which apart from complaining about functions in a loop and declaring var iwith var arrayreturned little help. I'm relatively inexperienced with javascript so thought perhaps a variable can't be used twice within a loop? Other than that, maybe something to do with using an id within a loop?

第一个未循环的版本有效。但是当我添加一个循环时它没有。该$getJSON部分执行,但随后无法将结果数据添加到 id。我跑了它通过的JSLint其中除了抱怨在一个循环的功能,并宣布var ivar array返回的帮助不大。我对 javascript 相对缺乏经验,所以认为一个变量可能不能在循环中使用两次?除此之外,也许与在循环中使用 id 有关?

回答by Denys Séguret

That's a classical problem : ihas the value of end of loop when the callback is called.

这是一个经典问题:i调用回调时具有循环结束的值。

You can fix it like this :

你可以像这样修复它:

for (var i = 0; i < array.length; i++) {
    (function(i) { // protects i in an immediately called function
      $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
      });
    })(i);
}

2018 addendum:

2018 年附录:

There's now another cleaner solution in today's browsers: use letinstead of var:

在当今的浏览器中,现在有另一种更简洁的解决方案:使用let代替var

for (let i = 0; i < array.length; i++) {
    $.getJSON('/api.php?action=query&list=querypage&qppage=' + array[i] + '&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
    });
}

回答by Girish

getJSON is an asynchronousajax call

getJSON 是一个异步ajax 调用

REFER: use synchronous ajax calls

REFER:使用同步ajax调用

回答by user2973469

Use Jquery $.each()to iterate over the array instead of a for loop.

使用 Jquery $.each()迭代数组而不是 for 循环。

For example:

例如:

$.each(array, function(_, value) {
    var url = '/api.php?action=query&list=querypage&qppage=' + value + '&format=json';

    $.getJSON(url, function (data) {
        $('#' + value).text(data.query.querypage.results.length);
    });
});

回答by Piyas De

You should write a function like -

你应该写一个函数,比如 -

function callUrl(value)
{
 $.getJSON('/api.php?action=query&list=querypage&qppage=' + value + '&format=json', function (data) {
        $('#' + value).text(data.query.querypage.results.length);
    });
}

and then call it with some timeout option like -

然后使用一些超时选项调用它,例如 -

setTimeout('callUrl(+ array[i] +)',500);within the loop -

setTimeout('callUrl(+ array[i] +)',500);在循环内 -

i.e.

IE

for (var i = 0; i < array.length; i++) {
  setTimeout('callUrl(+ array[i] +)',500);
}

Some delay for each call will be required here.

此处需要对每个呼叫进行一些延迟。