按照发送的顺序显示AJAX响应,而不使用排队或同步请求

Displaying AJAX responses in the same order in which they were sent out, *without* using queueing or synchronous requests?

本文关键字:排队 请求 同步 响应 顺序 AJAX 显示      更新时间:2023-09-26

我正在向远程服务器发送一堆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的类似问题,但没有一个像我正在寻找的那样具体。

谢谢。

EDIT -我现在要睡觉了,但我明天会回来的-如果可以的话,请回来看看。我真的很感激你的帮助。:)

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

$.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 + '" />');
    });
});

不附加ID,而是使用日期戳如何?通过这种方式,您可以真正按照请求发出的"时间"进行排序。如果您使用TinySort插件,您的临时div想法也可以很好地工作。

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

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"});
            });
        }
    });
});

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); 
    });
});

在做这样的事情时,有适当的CPS真的很有帮助。使用JooseX-CPS,您可以使用它的AND构造来并行化操作,保证返回值的正确顺序。这里有一个教程(点击Show me the parallel)