[英]JavaScript offset/pagination issue
I am calling to my local API and trying to do it in a pagination
style. 我正在调用本地API并尝试以
pagination
样式进行操作。 I have n
pictures that I want divided over n / 4
rows (4 pictures per row). 我有
n
张图片,我希望将其划分为n / 4
行(每行4张图片)。 So therefor, I am calling to my API, images/count,offset
. 因此,我正在调用我的API,
images/count,offset
。 But somehow I keep on getting the same results in console.log
, namely the first four images. 但是不知何故,我继续在
console.log
获得相同的结果,即前四个图像。
$(document).ready(function() {
var offset = 0;
var timesToRun = $('.container').data('rows');
var images = [];
for(var i = 1; i <= timesToRun; i++) {
$.ajax('http://192.168.10.11/images/4,' + offset, {
error: function(err) {
console.log(err);
},
method: 'GET',
success: function(data) {
console.log('http://192.168.10.11/images/4,' + offset);
offset = offset + 4;
var currentSet = [];
currentSet.push(data);
console.log(currentSet);
}
});
}
});
In Laravel I am pulling the number of images like so: 在Laravel中,我像这样拉动图像的数量:
public function selectWithOffset($count, $offset)
{
$selectionOfImages = \DB::table('images')->skip($offset)->take($count)->get();
return response()->json($selectionOfImages);
}
When I click the links I do receive the expected response. 当我单击链接时,我确实收到了预期的响应。 What might go wrong here?
这里可能出什么问题?
The problem is within your JavaScript. 问题出在您的JavaScript中。
$.ajax
is asynchronous by default. $.ajax
默认情况下是异步的。 The for loop will complete before any success callback of $.ajax is called, and this is the place where you increase the offset. for循环将在调用$ .ajax的任何成功回调之前完成,这是您增加偏移量的地方。
You have to options to fix this: 您必须选择解决此问题的方法:
1. Make $.ajax synchronous 1.使$ .ajax同步
Add async: false
to the $.ajax options. 在$ .ajax选项中添加
async: false
。
$.ajax('http://192.168.10.11/images/4,' + offset, {
error: function(err) {
console.log(err);
},
async: false,
method: 'GET',
success: function(data) {
// ...
}
});
2. Increment offset
outside of the success callback 2.成功回调之外的增量
offset
for(var i = 1; i <= timesToRun; i++) {
$.ajax('http://192.168.10.11/images/4,' + offset, {
// ...
});
// Increment offset
offset += 4;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.