我正在向远程服务器发送一堆 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).
我已经搜索过了,虽然有类似的问题 https://stackoverflow.com/questions/5241254/how-to-ensure-ajax-requests-called-in-a-certain-order-get-the-response-in-the-sam关于这里的 AJAX,没有一个像我正在寻找的那样具体。
Thanks.
EDIT- 刚刚去睡觉,但我明天会回来 - 如果可以的话,请回来查看。我真的很感谢你的帮助。 :)