我正在向远程服务器发送一堆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);
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
我已经尝试创建一堆新的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 …Run Code Online (Sandbox Code Playgroud)