How to stop AJAX calls if there's an error on a field with a keyup trigger

≯℡__Kan透↙ 提交于 2019-12-11 19:15:24

问题


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:


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)



来源:https://stackoverflow.com/questions/13387958/how-to-stop-ajax-calls-if-theres-an-error-on-a-field-with-a-keyup-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!