如何在用户清除文本字段时延迟java脚本keyup()处理程序

时间:2017-11-19 05:01:18

标签: javascript php keyup onkeyup

我在单个文本框中使用JavaScript keyup()事件。

如果有人键入“Windows”,它会为每个键盘发送一个HTTP请求:

  

“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”

这是理想的行为。

当用户清空文本框时,会出错。

这是不受欢迎的行为。

问题

如何在清除文本框时停止发送HTTP请求?

2 个答案:

答案 0 :(得分:0)

在提出请求之前检查value

function getResult(elem) {

  if (elem.value !== '') {

    console.log('Have values')
  } else {

    console.log('No values')
  }


}
<input type="text" onkeyup="getResult(this)">

答案 1 :(得分:0)

您可以使用AJAX向服务器发送信息(并获取相关信息):

<?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>