的JavaScript / jQuery的 - 做一个AJAX请求,当用户键入一个textarea [英] JavaScript / jQuery - Make an AJAX request when a user is typing in a textarea

查看:97
本文介绍了的JavaScript / jQuery的 - 做一个AJAX请求,当用户键入一个textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,人们输入一些文字(自然),我希望把它使一个AJAX请求是由每一个现在,然后得到关于什么的文本区域大约是(像堆栈溢出的相关问题提出了一些建议,但对于一个文本区域,而不是一个文本输入)。问题是,我不能这样做,在每一个关键preSS AJAX请求(它会是无用的,非常消耗资源),我不知道什么是最有效的方法来做到这一点(每X字?每X秒?还是其他什么东西?)。

I have a textarea where people enter some text (naturally), and I want to make it so that an AJAX request is made every now and then to get some suggestions regarding what the textarea is about (like stack overflow's Related Questions, but for a textarea, not a text input). The problem is that I can't do an AJAX request at every keypress (it'd be useless and very resource consuming), and I am not sure what would be the most efficient way to do it (every X words? every X seconds? or something else?).

什么是去这样做的最好方法是什么?

What would be the best way to go about doing this?

感谢你在前进。

推荐答案

您可以结合一个键preSS 事件处理的setTimeout 让您发送一个Ajax请求一个设定的时间量后的一个关键preSS,取消,如果另一个关键preSS计时器结束之前发生重启定时器。假设你有一个ID为myTextArea和一个名为Ajax的回调函数,一个textarea doAjaxStuff

You could combine a keypress event handler with setTimeout so that you send an Ajax request a set amount of time after a keypress, cancelling and restarting the timer if another keypress occurs before the timer finishes. Assuming you have a textarea with id 'myTextArea' and an Ajax callback function called doAjaxStuff:

function addTextAreaCallback(textArea, callback, delay) {
    var timer = null;
    textArea.onkeypress = function() {
        if (timer) {
            window.clearTimeout(timer);
        }
        timer = window.setTimeout( function() {
            timer = null;
            callback();
        }, delay );
    };
    textArea = null;
}

addTextAreaCallback( document.getElementById("myTextArea"), doAjaxStuff, 1000 );

这篇关于的JavaScript / jQuery的 - 做一个AJAX请求,当用户键入一个textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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