Javascript 当用户清除文本字段时,如何延迟java脚本keyup()处理程序
我正在使用JavaScriptJavascript 当用户清除文本字段时,如何延迟java脚本keyup()处理程序,javascript,php,keyup,onkeyup,Javascript,Php,Keyup,Onkeyup,我正在使用JavaScriptkeyup()事件作为单个文本框 如果有人键入“Windows”,它将为每个密钥更新发送HTTP请求: “W”、“Wi”、“Win”、“Wind”、“Windo”、“Window”、“Windows” 这是理想的行为 当用户将文本框清除为空时,将显示一个错误 这是不受欢迎的行为 问题 清除文本框后,如何停止发送HTTP请求?在发出请求之前,请检查值 函数getResult(elem){ 如果(元素值!=''){ console.log('Have values')
keyup()
事件作为单个文本框
如果有人键入“Windows”,它将为每个密钥更新发送HTTP请求:
“W”、“Wi”、“Win”、“Wind”、“Windo”、“Window”、“Windows”
这是理想的行为
当用户将文本框清除为空时,将显示一个错误
这是不受欢迎的行为
问题
清除文本框后,如何停止发送HTTP请求?在发出请求之前,请检查
值
函数getResult(elem){
如果(元素值!=''){
console.log('Have values')
}否则{
console.log('无值')
}
}
您可以使用AJAX向服务器发送信息(并获取相关信息):
document.getElementById(“搜索”).addEventListener('keyup',函数(e){
var xhr=new XMLHttpRequest();
xhr.open(“POST”和“#”,true);
setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
xhr.onreadystatechange=函数(){
if(xhr.readyState==XMLHttpRequest.DONE){
如果(xhr.readyState==4&&xhr.status==200){
object=JSON.parse(xhr.responseText);
console.log(对象);
}
}
}
xhr.send(“search=“+this.value”);
});
显示您的代码。您可以检查用户inut的文本长度,然后开始search@LasanthaHerath令人惊叹的!如果你能将它标记为解决方案,那会有很大帮助,请选择一个好的解决方案。
<?php
if (isset($_POST['search'])) {
echo json_encode($_POST);
die();
}
?>
<form>
<input id="search" type="text" name="search" />
</form>
<script>
document.getElementById("search").addEventListener('keyup', function (e) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "#", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.readyState == 4 && xhr.status == 200) {
object = JSON.parse(xhr.responseText);
console.log(object);
}
}
}
xhr.send("search=" + this.value);
});
</script>