在一个脚本中有两个$ .ajax()调用 [英] Having two $.ajax() calls in one script

查看:104
本文介绍了在一个脚本中有两个$ .ajax()调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示一些服务器端过程的进度信息(实际上是ffmpeg重新编码). 我最好的方法是在myscript上使用两个不同的$ .ajax()调用,如下所示:

I want to show some progress information of a server side procedure (which in fact is an ffmpeg re-encoding). The best way I though of was to use two different $.ajax() calls on myscript like this:

1)提交表单时(将触发重新编码),一个$ .ajax()将开始重新编码,如下所示:

1) when the form is submitted (which would trigger the re-encoding) one $.ajax() would start the re-encoding like this:

   $.ajax({  
    type: "GET",  
    url: "runffmpeg.php",  
    data: dataString,  
    success: function(data, textStatus, XMLHttpRequest) {  
            //clearInterval(repeat);
            location.reload(); 
        }});

2)然后,第二个$ .ajax()调用将开始查看结果文件的大小,以将进度告知访问者,如下所示:

2) Then, a second $.ajax() call would start watching the resulted file's size in order to inform the visitor of the progress, like this:

    $.ajax({  
        type: "GET",  
        url: "checkprogress.php",  
        data: dataString,  
        success: function(data, textStatus, XMLHttpRequest) {                   
                $('#submitted').html(data);
            }
    });

实际上,应该在1秒的setInterval内进行此调用,以显示进度.

Actually this call I should be made within an setInterval of an 1 second period in order to show the progression.

当然这是行不通的(否则我为什么要发布它)并且我找不到同时进行2个Ajax调用的任何参考.

Of course this doesn't work (or else why I should I posted it) and I can't find any reference of having 2 ajax calls on the same time.

推荐答案

同时接受两个ajax调用是完全可以接受的. 但是,我使用setInterval,因为如果返回时间超过一秒,您可能最终会多次调用checkprogress.php.您最好让成功方法在超时后启动新的ajax请求,例如:

It's perfectly acceptable to have two ajax calls at the same time. I would however not use setInterval, as you might end up with multiple calls to checkprogress.php if it takes more than a second to return. You're better off having the success method launch a new ajax request, perhaps after a timeout, eg:

function checkProg(){
  $.ajax({  
      type: "GET",  
      url: "checkprogress.php",  
      data: dataString,  
      success: function(data, textStatus, XMLHttpRequest) {                   
              $('#submitted').html(data);
              if (/* not yet complete */) {
                setTimeout(checkProg,500);
              }
          }
  });
}

这篇关于在一个脚本中有两个$ .ajax()调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆