jQuery Ajax / .each 回调,下一个“each”在ajax完成之前触发

发布于 2024-10-08 10:33:41 字数 1207 浏览 2 评论 0原文

您好,当我提交表单时,会调用下面的 Javascript。它首先从文本区域中分割出一堆 url,然后:

1) 为每个 url 添加行到表中,并在最后一列(“状态”列)中显示“未开始”。
2) 它再次循环遍历每个 url,首先它会进行 ajax 调用来检查状态 (status.php),这将返回 0 - 100 之间的百分比。
3)在同一个循环中,它通过ajax(process.php)启动实际流程,当流程完成时(记住持续的状态更新),它会在状态栏中显示“已完成”并退出自动刷新。
4) 然后它应该转到下一个“each”并对下一个 url 执行相同的操作。

function formSubmit(){

    var lines = $('#urls').val().split('\n');

    $.each(lines, function(key, value) {
        $('#dlTable tr:last').after('<tr><td>'+value+'</td><td>Not Started</td></tr>');
    });

    $.each(lines, function(key, value) {

        var auto_refresh = setInterval( function () {
            $.ajax({
              url: 'status.php',
              success: function(data) {
            $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>"+data+"</td>");
              }
            });
        }, 1000);

        $.ajax({
          url: 'process.php?id='+value,
          success: function(msg) {
        clearInterval(auto_refresh);
        $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>completed rip</td>");
          }
        });

    });

}

Hi the below Javascript is called when I submit a form. It first splits a bunch of url's from a text area, it then:

1) Adds lines to a table for each url, and in the last column (the 'status' column) it says "Not Started".
2) Again it loops through each url, first off it makes an ajax call to check on the status (status.php) which will return a percentage from 0 - 100.
3) In the same loop it kicks off the actual process via ajax (process.php), when the process has completed (bearing in the mind the continuous status updates), it will then say "Completed" in the status column and exit the auto_refresh.
4) It should then go to the next 'each' and do the same for the next url.

function formSubmit(){

    var lines = $('#urls').val().split('\n');

    $.each(lines, function(key, value) {
        $('#dlTable tr:last').after('<tr><td>'+value+'</td><td>Not Started</td></tr>');
    });

    $.each(lines, function(key, value) {

        var auto_refresh = setInterval( function () {
            $.ajax({
              url: 'status.php',
              success: function(data) {
            $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>"+data+"</td>");
              }
            });
        }, 1000);

        $.ajax({
          url: 'process.php?id='+value,
          success: function(msg) {
        clearInterval(auto_refresh);
        $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>completed rip</td>");
          }
        });

    });

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

書生途 2024-10-15 10:33:41

您想要的是按顺序运行多个异步操作,对吗?我将构建一个函数数组来执行并通过序列助手运行它。

https://github.com/michiel/asynchelper-js/blob /master/lib/sequencer.js

var actions = [];
$.each(lines, function(key, value) {

    actions.push(function(callback) {
      $.ajax({
          url: 'process.php?id='+val,
          success: function(msg) {
            clearInterval(auto_refresh);

            //
            // Perform your DOM operations here and be sure to call the
            // callback!
            //

            callback();
          }
        });
    });
  }
);

如您所见,我们构建了一个作用域函数数组,这些函数接受任意回调作为参数。定序器将为您按顺序运行它们。

使用 github 链接中的序列助手并运行,

var sequencer = new Sequencer(actions);
sequencer.start();

顺便说一句,可以在几行代码中定义序列器函数。例如,

function sequencer(arr) {
    (function() {
        ((arr.length != 0) && (arr.shift()(arguments.callee)));
    })();
}

What you want is to run several asynchronous actions in sequence, right? I'd build an array of the functions to execute and run it through a sequence helper.

https://github.com/michiel/asynchelper-js/blob/master/lib/sequencer.js

var actions = [];
$.each(lines, function(key, value) {

    actions.push(function(callback) {
      $.ajax({
          url: 'process.php?id='+val,
          success: function(msg) {
            clearInterval(auto_refresh);

            //
            // Perform your DOM operations here and be sure to call the
            // callback!
            //

            callback();
          }
        });
    });
  }
);

As you can see, we build an array of scoped functions that take an arbitrary callback as an argument. A sequencer will run them in order for you.

Use the sequence helper from the github link and run,

var sequencer = new Sequencer(actions);
sequencer.start();

It is, btw, possible to define sequencer functions in a few lines of code. For example,

function sequencer(arr) {
    (function() {
        ((arr.length != 0) && (arr.shift()(arguments.callee)));
    })();
}
要走干脆点 2024-10-15 10:33:41

AJAX 是异步

这正是应该发生的事情。

您应该在前一个 AJAX 请求的完成处理程序中发送下一个 AJAX 请求,而不是使用 each

AJAX is asynchronous.

That's exactly what's supposed to happen.

Instead of using each, you should send the next AJAX request in the completion handler of the previous one.

长途伴 2024-10-15 10:33:41

您还可以使用“async”属性将 AJAX 设置为同步运行。添加以下内容:

$.ajax({ "async": false, ... other options ... });

AJAX API 参考此处。请注意,这将锁定浏览器,直到请求完成。

我更喜欢 SLAks 答案中的方法(坚持异步行为)。但是,这确实取决于您的应用程序。谨慎行事。

You can also set AJAX to run synchronously using the "async" property. Add the following:

$.ajax({ "async": false, ... other options ... });

AJAX API reference here. Note that this will lock the browser until the request completes.

I prefer the approach in SLaks answer (sticking with asynchronous behavior). However, it does depend on your application. Exercise caution.

铁轨上的流浪者 2024-10-15 10:33:41

我会给出与此相同的答案 jquery json populate table

此代码将给出您知道如何将回调与循环和 ajax 一起使用。但我没有测试过,肯定会有bug。我从旧代码中得出以下结论:-

var processCnt; //Global variable - check if this is needed
function formSubmit(){

    var lines = $('#urls').val().split('\n');

    $.each(lines, function(key, value) {
        $('#dlTable tr:last').after('<tr><td>'+value+'</td><td>Not Started</td></tr>');
    });

    completeProcessing(lines ,function(success)
    {
           $.ajax({
          url: 'process.php?id='+value,
          success: function(msg) {
                $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>completed rip</td>");
          }
        });


    });


}

//Following two functions added by me
function completeProcessing(lines,callback)
{
    processCnt= 0;
    processingTimer = setInterval(function() { singleProcessing(lines[processCnt],function(completeProcessingSuccess){ if(completeProcessingSuccess){ clearInterval(processingTimer); callback(true); }})}, 1000);    

}


function singleProcessing(line,callback)
 {
    key=processCnt;
    val = line;
    if(processCnt < totalFiles)
    { //Files to be processed

        $.ajax({
                  url: 'status.php',
                    success: function(data) {
                           $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>"+data+"</td>");
                      processCnt++; 
                      callback(false); 

                    }
                });
    }
    else
    {
        callback(true);

    }       
}

I would give the same answer as this jquery json populate table

This code will give you a little idea how to use callback with loops and ajax. But I have not tested it and there will be bugs. I derived the following from my old code:-

var processCnt; //Global variable - check if this is needed
function formSubmit(){

    var lines = $('#urls').val().split('\n');

    $.each(lines, function(key, value) {
        $('#dlTable tr:last').after('<tr><td>'+value+'</td><td>Not Started</td></tr>');
    });

    completeProcessing(lines ,function(success)
    {
           $.ajax({
          url: 'process.php?id='+value,
          success: function(msg) {
                $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>completed rip</td>");
          }
        });


    });


}

//Following two functions added by me
function completeProcessing(lines,callback)
{
    processCnt= 0;
    processingTimer = setInterval(function() { singleProcessing(lines[processCnt],function(completeProcessingSuccess){ if(completeProcessingSuccess){ clearInterval(processingTimer); callback(true); }})}, 1000);    

}


function singleProcessing(line,callback)
 {
    key=processCnt;
    val = line;
    if(processCnt < totalFiles)
    { //Files to be processed

        $.ajax({
                  url: 'status.php',
                    success: function(data) {
                           $('#dlTable').find("tr").eq(key+1).children().last().replaceWith("<td>"+data+"</td>");
                      processCnt++; 
                      callback(false); 

                    }
                });
    }
    else
    {
        callback(true);

    }       
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文