开发者

To continually pull result from the server via Ajax until timeout or getting result

I would like to make an Ajax request to the server, which replies a job status and result. If the status is "Error" or "Ok", the client should show the result (containing HTML code) to the user. However, if the status is "Waiting", the client should wait for a few seconds and then automatically send the same Ajax request开发者_开发问答 again. This should continue until it either times out or gets a "Error"/"OK" message.

Any idea for a solution/code snippet like this? I am currently using Rails, JQuery, and Prototype. Many thanks.

Mountain


You can do like

(function refresh(){
   $.ajax({
      url:      '/myfile',
      data:     'data',
      dataType: 'text',
      type:     'POST',
      success:   function(data){
          if(data === 'Waiting')
             setTimeout(refresh, 5000);
          else
             alert(data);
      }
   });
})();

That would initiate a self-executing anonymous function with an ajax request. If the returned string equals Waiting it will set a timeout for 5 seconds and calls itself again.


Without fully understanding the context of your application I would think you need to make sure that getting the response from the server is not critical is that you may not necessary rely on the retry to occur in the "Waiting" response case. For example, if the user navigates away from the page the script may be unloaded and the retry would not then occur.

If, as it seems, you are anticipating possibly long running jobs it might be best just to return a HTTP status OK and allow the content to be retrieved at a later point either synchronously or asynchronously as appropriate.

You might also consider delivering the response using HTTP header attributes rather than inlined with your response data.


Javascript:

var t = setInterval('checkServer', 5000)

function checkServer() {

  $.ajax({
    url: 'yoururl',
    data: params,
    success: function(resp) {
      if(resp == "Error" || resp == "OK") {
        alert(resp);
        clearInterval(t);
      }
    }
  });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜