Big*_*rey 6 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);
});
}
});
});
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 shove the responses into "#img_$i" using the iterator variable to "keep track" (which didn't work).
Run Code Online (Sandbox Code Playgroud)
我已经搜索过了,虽然这里有关于AJAX的类似问题,但没有一个像我想要的那样具体.
谢谢.
编辑 - 刚刚上床但明天我会回来 - 如果可以的话,请回来查看.我非常感谢你的帮助.:)
你快到了; 只需要以divAjax回调函数可以引用相应的方式创建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 + '" />');
});
});
Run Code Online (Sandbox Code Playgroud)