$getJSON and for loop issue

后端 未结 4 1847
野性不改
野性不改 2020-12-01 10:01

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=BrokenRedirec

相关标签:
4条回答
  • 2020-12-01 10:26

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

    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);
        });
    });
    
    0 讨论(0)
  • 2020-12-01 10:32

    getJSON is an asynchronous ajax call

    REFER: use synchronous ajax calls

    0 讨论(0)
  • 2020-12-01 10:32

    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 -

    i.e.

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

    Some delay for each call will be required here.

    0 讨论(0)
  • 2020-12-01 10:34

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

    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:

    There's now another cleaner solution in today's browsers: use let instead of 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);
        });
    }
    
    0 讨论(0)
提交回复
热议问题