How to stop AJAX calls if there's an error on

2019-08-21 07:09发布

I have this jquery ajax call that is trigger on keyup. It has error handling which (with Firefox for e.g.) is triggered multiples times if the user enters keystrokes fast. Is there a quick way to stop multiple alert windows to be shown?

$('input[name$="_LOC"]').keyup(function(){

    if ($(this).val().length >=4){

        $.ajax({
            type: 'POST',
            url: 'red.asp?q='+$(this).val(),
            beforeSend: function() {
                    [...]   
            },
            success: function(data) {
                [...]
            },
            error: function() {
                alert("Oops!")
            }
        }); 
    }
});

1条回答
▲ chillily
2楼-- · 2019-08-21 07:16

Restart a timer each time the onkeyup is triggered, this means the event only happens when the user has finished typing (or, at least, paused for a second or whatever).

Use timer = setTimeout(yourFunction, yourDelay);

To rest the timer user clearInterval(timer) and start the setTimeout again.

var typing = false;
var timer;

$('input[name$="_LOC"]').keyup(function(){
 if(typing) {
   clearInterval(timer);

 }
timer = setTimeout(sendAjax, 500, [this]);
 typing=true;
});

function sendAjax(element) 
{
    if ($(element).val().length >=4){

        $.ajax({
            type: 'POST',
            url: 'red.asp?q='+$(element).val(),
            beforeSend: function() {
                    [...]   
            },
            success: function(data) {
                [...]
            },
            error: function() {
                alert("Oops!")
            }
        }); 
    typing = false;   
   }

Here's JSFiddle example: http://jsfiddle.net/X8US5/, you'll need your browsers console.log viewer ready to see stuff (otherwise edit the console.logs to be alerts though they interrupt JS so times will be off)

Edit: IE9 compatible (hack) version http://jsfiddle.net/5ndM5/1/ Tried to find a jQuery alternative but none it seems. THe overriding the function alternative is good if you don't want the global var, but if you only plan to use this code on one form then the global is acceptable (JS code is usually rife with them by accident anyway)

查看更多
登录 后发表回答