Having two $.ajax() calls in one script

2019-09-05 15:36发布

问题:

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

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

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.

回答1:

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


回答2:

There is a limit on how many ajax requests can be active at the same time. This is browser dependant and should be something close to 3. I believe that it is possible to have two requests active at the same time, but this isn't recommended.

What I propose is to re-design your server code to immediately reply to the form submission, acknowledging the reception of the command. Then use polling for displaying the progress.