以与发送它们相同的顺序显示AJAX响应,*没有*使用排队或同步请求?

时间:2011-04-26 23:09:58

标签: javascript ajax jquery

我向远程服务器发送了一堆getJSON()请求(用于获取图像),我想按照发送请求的相同顺序显示响应(图像)。问题是,AJAX是异步的,因此响应以他们想要的顺序出现 - 通常都是混合的。

我可以将它们排队或使它们同步 - 一次只发出一个请求 - 但这会严重限制性能。

那么有什么方法可以在响应回来时确定哪个响应属于哪个请求?我想你可以把一个“id”变量放入JSON回调参数(例如callback = response03),然后以某种方式解析响应到达时的回调函数名称(从而获取id,“03”)。但可能不是。

我的代码是这样的:

// Send off requests for each keyword string
$.each($imageRequests, function() {
    $request = this;
    $url = "http://www.example.com/api?q="+$url;
    $.getJSON($url, function($response) {
        if($response.data.items) {
            $.each($response.data.items, function($i, $data) {
                $imgUrl = $data.url;
                $("#imageList").append($imgUrl);
            });
        }
    });
});

我已经尝试创建一堆新的div来保存返回的图像,以为我可以使用各自的图像填充div,但这也不起作用。

// Create new div with unique id using line number
$i = 0;
$.each($lines, function() {
    $newDiv = '<div id="img_'+$i+'"></div>';
    $("#imageList").append($newDiv);
    $i++;
});

// Then do the same as the code above but shove the responses into "#img_$i" using the iterator variable to "keep track" (which didn't work).

我已经搜索了,虽然这里有关于AJAX的similar questions,但没有一个像我正在寻找的那样具体。

感谢。

编辑 - 刚刚上床睡觉但明天我会回来 - 如果可以的话,请回来看看。我非常感谢你的帮助。 :)

4 个答案:

答案 0 :(得分:6)

你快到了;只需要以Ajax回调函数可以引用相应的div的方式创建div,即使用closure。像这样:

$.each(urls, function(i, url) {
    var div = $('<div />');
    list.append(div); // list is the container element that holds the images

    $.getJSON(url, function(data) {
        // assuming data is an image url - adjust accordingly
        div.append('<img src="' + data + '" />');
    });
});

答案 1 :(得分:0)

而不是附加ID,而不是日期戳呢? 通过这种方式,您可以根据请求的“时间”进行排序。如果你使用TinySort插件,你的临时想法也可以很好地工作。

在其他地方创建一个时间戳变量..

var stamp = new Date();

然后将毫秒附加到每个请求。

$.each($imageRequests, function() {
    $request = this;
    $url = "http://www.example.com/api?q="+$url+"&stamp="+stamp.getMilliseconds();
    $.getJSON($url, function($response) {
        if($response.data.items) {
            $.each($response.data.items, function($i, $data) {
                $url = '<img alt="'+ $data.stamp +'" src="'+ $data.url +'" />';
                $("#tempdiv").append($url);

                // After appending, you can sort them
                $("#tempdiv").tsort("img",{order:"desc",attr:"alt"});
            });
        }
    });
});

答案 2 :(得分:0)

jQ中的

each()回调有一个参数 - 元素索引或迭代次数。 因此,您可以预先创建s数组,并在到达时设置/修改该索引处的div:

var divs = $("div.your-class");
$.each($imageRequests, function(irIndex) {
    $.getJSON(url, function(response) {
     // change element at irIndex using the response.
     divs[irIndex].someUpdate(response); 

    });
});

答案 3 :(得分:0)

在做这样的事情时,拥有适当的CPS真的很有帮助。使用JooseX-CPS,您可以使用其AND构造来并行化操作,从而保证返回值的正确顺序。这是一个tutorial(查看告诉我的并列)。