简体   繁体   English

如何通过列表运行$ .ajax?

[英]How can I run $.ajax through a list?

When I run $.ajax multiple times, it doesn't seem to wait for the ajax call to finish before continuing to run my code. 当我多次运行$ .ajax时,似乎没有等待ajax调用完成才继续运行代码。 As I am using jsonp, setting 'async: false' doesn't work (or so I've read). 当我使用jsonp时,设置'async:false'不起作用(或者我已经读过)。 I have to jsonp to access the Media Wiki api, so changing that isn't an option. 我必须jsonp才能访问Media Wiki api,因此更改它不是一个选择。 I am a beginner at Javascript, is this something I could use a 'promise' for? 我是Java语言的初学者,这是否可以用作“承诺”?

var articleList = ['Abaft', 'Aspect-oriented%20programming', 'Defecation', 'Feces', 'Perl%20Object-Oriented%20Persistence', 'Poop%20(constellation)', 'Poop%20deck', 'Pooper-scooper', 'Poopy', 'Stern', 'Zoboomafoo'];

function retrieveSummary(jsonp) {
  console.log(jsonp);
}

function fetchSummary() {
  for (var article in articleList) {
    $.ajax({
      url: 'https://en.wikipedia.org/w/api.php?action=parse&page=' + article + '&prop=text&format=json&section=0&callback=?',
      dataType: 'jsonp',
      contentType: 'application/json',
      jsonpCallback: 'retrieveSummary',
    });
  }
}

The output I get is the jsonp object of 'Poop (constellation)', which is in the middle of the list. 我得到的输出是列表中间的“ Poop(星座)”的jsonp对象。 That's the only object I get, despite calling the callback function for each article in articleList. 尽管为articleList中的每篇文章调用了回调函数,但这都是我唯一的对象。

Have a look on jQuery documentation on how $.when() function works, I think that may help you :) 看一下$ .when()函数如何工作的jQuery文档,我认为这可能对您有帮助:)

Btw, avoid using async: false unless you are 100% sure that you need a sync call that can't be archieved with $.when().done/then/always 顺便说一句,避免使用async:false除非您100%确定需要一个不能用$ .when()。done / then / always存档的同步调用

As @charlietfl pointed, async: false doesn't work with jsonp calls. 正如@charlietfl指出的那样,async:false不适用于jsonp调用。

From jQuery Documentation: 从jQuery文档中:

By default, all requests are sent asynchronously (ie this is set to true by default). 默认情况下,所有请求都是异步发送的(即默认情况下设置为true)。 If you need synchronous requests, set this option to false. 如果需要同步请求,请将此选项设置为false。 Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation 跨域请求和dataType:“ jsonp”请求不支持同步操作

Try something like this (untested): 尝试以下操作(未经测试):

var articleList = ['Abaft', 'Aspect-oriented%20programming', 'Defecation', 'Feces', 'Perl%20Object-Oriented%20Persistence', 'Poop%20(constellation)', 'Poop%20deck', 'Pooper-scooper', 'Poopy', 'Stern', 'Zoboomafoo'];

Promise.all(articleList.map(function(article) {
    return $.ajax({
        url: 'https://en.wikipedia.org/w/api.php?action=parse&page=' + article + '&prop=text&format=json&section=0&callback=?',
        dataType: 'jsonp',
        contentType: 'application/json',
    });
  })).then(function(results) {
    console.log(results);
});

The ajax call returns a promise, Promise.all waits until all promises are resolved then calls back. Ajax调用返回一个Promise.Promise.all,直到所有的Promise被解决,然后再回调。

Try my example. 试试我的例子。

function Timer() {
    this.interval = 1000;
    this.maxloop = 0; //max loop.
    this.onTimerLoop = function () {
    };
    this.onTimerStop = function () {
    };
    var global = this;
    var count = 0;
    var taskID = -1;
    var isWorking = false;
    this.start = function () {
        if (taskID === -1) {
            count = 0;
            isWorking = false;
            taskID = window.setInterval(function () {


                if (!isWorking) {
                    count += 1;
                    isWorking = true;
                    if (global.maxloop > 0 && (count > global.maxloop)) {
                        global.stop();
                    } else {
                        global.onTimerLoop();
                    }
                    isWorking = false;
                }


            }, global.interval);
        }

    };
    this.stop = function () {
        if (taskID !== -1) {
            window.clearInterval(taskID);
            taskID = -1;
            global.onTimerStop();
        }
    };



}

var articleList = ['Abaft', 'Aspect-oriented%20programming', 'Defecation', 'Feces', 'Perl%20Object-Oriented%20Persistence', 'Poop%20(constellation)', 'Poop%20deck', 'Pooper-scooper', 'Poopy', 'Stern', 'Zoboomafoo'];
var timer = new Timer();
timer.interval = 300;
var currentPositionArticle = 0;
var lastCurrentPositionArticle = -1;
timer.onTimerLoop = function () {
    if (currentPositionArticle !== lastCurrentPositionArticle) {
        lastCurrentPositionArticle = currentPositionArticle;
        $.ajax({
            url: 'https://en.wikipedia.org/w/api.php?action=parse&page=' + articleList[currentPositionArticle] + '&prop=text&format=json&section=0&callback=?',
            dataType: 'jsonp',
            contentType: 'application/json',
            jsonpCallback: "retrieveSummary"
        });

        if (currentPositionArticle === articleList.length - 1) {
            timer.stop();
        }
    }
};
timer.start();

function retrieveSummary(jsonp) {
    currentPositionArticle++;
    alert(jsonp);
    wait = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM