JavaScript偏移/分页问题

I am calling to my local API and trying to do it in a pagination style. I have n pictures that I want divided over n / 4 rows (4 pictures per row). So therefor, I am calling to my API, images/count,offset. But somehow I keep on getting the same results in console.log, namely the first four images.

$(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:

public function selectWithOffset($count, $offset)
    {
        $selectionOfImages = \DB::table('images')->skip($offset)->take($count)->get();
        return response()->json($selectionOfImages);
    }

Current console output

When I click the links I do receive the expected response. What might go wrong here?

The problem is within your JavaScript. $.ajax is asynchronous by default. The for loop will complete before any success callback of $.ajax is called, and this is the place where you increase the offset.

You have to options to fix this:

1. Make $.ajax synchronous

Add async: false to the $.ajax options.

$.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

for(var i = 1; i <= timesToRun; i++) {

    $.ajax('http://192.168.10.11/images/4,' + offset, {
        // ...
    });

    // Increment offset
    offset += 4;

}