简体   繁体   English

使用多个jquery .get()不会按顺序返回数据?

[英]Getting using multiple jquery .get() doesn't return the data in sequence?

Like the title says, I'm using multiple url's to get my data from and I'm using the jquery .get() method. 就像标题所说,我正在使用多个url来获取我的数据,而我正在使用jquery .get()方法。 For example: 例如:

var m=0;
$.get(url1).done(function(data) 
{
    list[m] = data;
    m++;
}
$.get(url2).done(function(data) 
{
    list[m] = data;
    m++;
}
$.get(url3).done(function(data) 
{
    list[m] = data;
    m++;
}
$.get(url4).done(function(data) 
{
    list[m] = data;
    m++;
}

I have four url's there and I'm putting the data into a array list[] . 我有四个url,我将数据放入数组list[] I will need the data to be in sequence, meaning list[1] comes from url1, list[2] from url2 and so on. 我需要数据按顺序排列,这意味着list[1]来自url1, list[2]来自url2,依此类推。

But the problem is, it's not always in sequence. 但问题是,它并不总是按顺序排列。 Sometimes I get data like list[1] from url4 or list[2] from url1. 有时我从url4获取list[1]或url1中的list[2]数据。 Seems like using multiple .get() functions does not always return the data in sequence. 似乎使用多个.get()函数并不总是按顺序返回数据。 Do you guys know how to get the data return in sequence using the .get() function? 你们知道如何使用.get()函数按顺序返回数据吗?

AJAX is asynchronous, and the responses can come in a different order than the order you sent the requests. AJAX是异步的,响应的顺序可以与发送请求的顺序不同。

One solution is to make m a closure variable that's set at the time you send the request, so you can then fill in the correct list element: 一种解决方案是使m成为在发送请求时设置的闭包变量,这样您就可以填写正确的列表元素:

$.each([url1, url2, url3, url4], function(m, url) {
    $.get(url).done(function(data) {
        list[m] = data;
    });
});

One solution is to chain them all together so the success of one get fires off the next get. 一种解决方案是将它们全部链接在一起,这样一个人的成功就会触发下一次获取。 You could setup another function to be called as the callback when the last get completes. 您可以设置另一个函数,在最后一次完成时调用它作为回调。 Something like this (haven't tested it) 像这样的东西(没有测试过)

var m=0;
$.get(url1).done(function (data) {
    list[m] = data;
    m++;

    $.get(url2).done(function (data) {
        list[m] = data;
        m++;

        $.get(url3).done(function (data) {
            list[m] = data;
            m++;

            $.get(url4).done(function (data) {
                list[m] = data;
                m++;
                alldone(data);
            });
        });
    });
});

function allDone(data) {
    //do this when last one completes
}

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

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