每当表单输入字段发生更改时,如何发送ajax请求? [英] How do you send an ajax request every time that a form input field changes?

查看:179
本文介绍了每当表单输入字段发生更改时,如何发送ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,有一个输入字段.每次用户在该字段中键入密钥时,它都会发送一个AJAX请求,其中包含该输入中当前包含的任何文本,并对其进行处理.我已经研究了Jquery中的change和keyup函数,但是当我在Jsfiddle中尝试它们时,它们什么也没做.有进行这种操作的标准方法吗?我知道它在验证和内容方面很常见.

For example, there is an input field. Every time a user types a key into that field, it sends an AJAX request with whatever text is currently in that input, and does something with it. I've looked into the change and keyup functions in Jquery, but when I try them in Jsfiddle they don't do anything. Is there a standard way of doing this type of operation? I know its common for validations and stuff.

<form>
    <input id="test" type='text' >
    <input type="submit" value="asdf">
</form>

$('input').on("change",(function(e){
    alert("Hello");
});

我想要的效果就像这个游戏www.sporcle.com/games/g/nflteams#

The effect I am going for is like this game www.sporcle.com/games/g/nflteams#

您可以输入任何文本,如果文本在正确答案集中,则表格将更新以显示该答案.您无需提交.您认为他们如何实现此效果?

You can type in any text and if its within the set of correct answers then the table will update to show that answer. You never have to submit. How do you suppose they achieved this effect?

在我看来,他们每次用户输入密钥时都必须查询数据库,以查看其是否为正确答案.如果是,他们将更新表格以显示答案.还有什么其他方法可以做到这一点?

It seemed to me like they must be querying the database every time a user enters a key, to see if it is a correct answer. If it is they update the table to display the answer. What are other ways to do this?

推荐答案

每次更改都发送请求很糟糕,延迟上一次更改的ajax

sending a request on each change is just bad, delay the ajax on the last change

var changeTimer = false;

$("your inputs").on("your change event",function(){
        if(changeTimer !== false) clearTimeout(changeTimer);
        changeTimer = setTimeout(function(){
            /* your ajax here */
            changeTimer = false;
        },300);
});

这篇关于每当表单输入字段发生更改时,如何发送ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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