如果使用keyup触发器的字段出现错误,如何停止AJAX调用 [英] How to stop AJAX calls if there's an error on a field with a keyup trigger

查看:127
本文介绍了如果使用keyup触发器的字段出现错误,如何停止AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个在keyup上触发的jquery ajax调用.它具有错误处理功能,如果用户快速输入击键,则会多次触发(例如,使用Firefox).有没有一种快速的方法来停止显示多个警报窗口?

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

推荐答案

每次触发onkeyup时都要重新启动计时器,这意味着该事件仅在用户完成键入(或至少暂停一秒钟或等等).

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).

使用timer = setTimeout(yourFunction, yourDelay);

要使计时器用户clearInterval(timer)休息并再次启动setTimeout.

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

这里是JSFiddle示例: http://jsfiddle.net/X8US5/,您将需要使用浏览器console.log查看器准备就绪,可以查看内容(否则将console.logs编辑为警报,尽管它们会中断JS,因此时间将关闭)

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)

修改: IE9兼容(hack)版本 http://jsfiddle.net/5ndM5/1/ 试图找到一个jQuery替代品,但似乎没有. 如果您不希望使用全局变量,则覆盖函数替代方法是很好的,但是如果您只打算在一种形式上使用此代码,则可以接受全局变量(无论如何,JS代码通常很容易出现在它们中)

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)

这篇关于如果使用keyup触发器的字段出现错误,如何停止AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆