开发者

How to prevent an ajax call when already it's been initiated?

Suppose there is a form. When the form is being submitted I'm calling an ajax reque开发者_开发技巧st to server. While it's being executing I don't want that ajax call to be triggered again. Once I the ajax call is complete then only the ajax call can be trigger again.

How can I implement this? Here I want to use JQUERY library to implement this.


Set a variable (in a scope that is wider than the function that initiates the Ajax call) to a value (such as true) when the function runs.

Set it to a different value when the callback runs.

If it is already set when the initial function runs, just return immediately.

var call_in_progress = false;

function myEventHandler(e) {
    if (call_in_progress) { return false; }
    call_in_progress = true;
    jQuery.ajax( etc etc myCallback );
}

function myCallback () {
    call_in_progress = false;
}


you can do it simply with some javascript variable.

Set it to true , when your operation begins. and set it to false again when the operation completes.

If any operation in parallel starts, that should check for the value of that variable and return if is it true without doing anything.

example:

var myOperationLocks = new Array();

function formPostByAjax()
{
   /* check for lock */
   if(myOperationLocks['form_post'] == true)
       return ;

   /* set the lock */
    myOperationLocks['form_post'] = true;
    /* do some work */
    jQuery.post(url,data,function(response) 
    {
      /* do something with response , then release the lock */
      myOperationLocks['form_post']  = false ; 
    }

}


Keep a variable that is set TRUE when the Ajax request is started. By checking this variable before each request is set.

To avoid killing operations on some trouble, such as no reply from the server, if the problem doesn't happen often you can throw up a "do you really want to" query. You could also have the variable hold the time, and if the time goes beyond some limit, allow it through again. But remember to clear the time variable once the Ajax completes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜