Javascript loop with ajax call

谁说胖子不能爱 提交于 2021-01-29 03:52:10

问题


I've been struggling all afternoon to understand how to make this work, hopefully someone can help. I have a simple requirement to run through a list of checked check boxes, retrieve some data from the server, fill an element with the data expand it. So far I have the following code;

function opentickedrows() {
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            tid = $(this).attr('name').replace("t_", "");
            $.ajax({
                url: '/transfer_list_details_pull.php?id=' + tid,
                type: 'GET',
                success: function (data) {
                    $('#r' + tid).html(data);
                    $("#r" + tid).show();
                    $("#box" + tid).addClass("row-details-open");
                }
            });
        }
    });
}

The problem that I am having is that the ajax calls all seem to happen so fast that 'tid' isn't being updated in the ajax call. From what I have read I believe I need to wrap this up into a couple of functions with a callback but I just can not get my head around how. I'd be really grateful if someone can set me on the right path.


回答1:


Ajax calls are asynchronous, so when the success callback is invoked, tid has the value of the last item of the $('input[type=checkbox]').

You could use a closure:

function opentickedrows() {
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            tid = $(this).attr('name').replace("t_", "");
            (function(tid) {
                $.ajax({
                    url: '/transfer_list_details_pull.php?id=' + tid,
                    type: 'GET',
                    success: function (data) {
                        $('#r' + tid).html(data);
                        $("#r" + tid).show();
                        $("#box" + tid).addClass("row-details-open");
                    }
                });
            })(tid)
        }
    });
}


来源:https://stackoverflow.com/questions/43191608/javascript-loop-with-ajax-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!