簡體   English   中英

JavaScript偏移/分頁問題

[英]JavaScript offset/pagination issue

我正在調用本地API並嘗試以pagination樣式進行操作。 我有n張圖片,我希望將其划分為n / 4行(每行4張圖片)。 因此,我正在調用我的API, images/count,offset 但是不知何故,我繼續在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);
            }

        });

    }

});

在Laravel中,我像這樣拉動圖像的數量:

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

當前控制台輸出

當我單擊鏈接時,我確實收到了預期的響應。 這里可能出什么問題?

問題出在您的JavaScript中。 $.ajax默認情況下是異步的。 for循環將在調用$ .ajax的任何成功回調之前完成,這是您增加偏移量的地方。

您必須選擇解決此問題的方法:

1.使$ .ajax同步

在$ .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.成功回調之外的增量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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM