Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有ajax调用的Javascript循环_Javascript_Ajax - Fatal编程技术网

带有ajax调用的Javascript循环

带有ajax调用的Javascript循环,javascript,ajax,Javascript,Ajax,我整个下午都在努力理解如何使这项工作顺利进行,希望有人能帮上忙。我有一个简单的要求,需要运行一个复选框列表,从服务器检索一些数据,用数据填充元素并展开它。到目前为止,我有以下代码 function opentickedrows() { $('input[type=checkbox]').each(function () { if (this.checked) { tid = $(this).attr('name').replace("t_", ""

我整个下午都在努力理解如何使这项工作顺利进行,希望有人能帮上忙。我有一个简单的要求,需要运行一个复选框列表,从服务器检索一些数据,用数据填充元素并展开它。到目前为止,我有以下代码

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");
                }
            });
        }
    });
}

我遇到的问题是,ajax调用似乎都发生得太快,以至于ajax调用中没有更新“tid”。从我所读到的内容来看,我相信我需要用回调函数将其封装成几个函数,但我就是不知道该怎么做。如果有人能让我走上正确的道路,我将不胜感激。

Ajax调用是异步的,因此当调用成功回调时,
tid
具有
$('input[type=checkbox]')最后一项的值。

您可以使用一个闭包:

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)
        }
    });
}

这是tid的范围问题;(您将其视为全球性问题)而不是“时间”或其他问题;i、 e.将其置于回调函数
success
的范围内,甚至添加
var tid=…
,以将其排除在该全局范围之外,但这确实使我们假设它不需要在此范围之外。