在 ajax 函数中使用 setInterval returns 'toLowerCase' 错误

using setInterval in ajax function returns 'toLowerCase' error

我试图每隔 x 秒调用一次这个函数,但是 returns 这个错误:

jquery.min.js:2 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

..什么?

这是代码:

$(document).ready(function update() {
  $.ajax({
    url: 'config/db.php',
    type: 'POST',
    data: {
      search: $(this).val()
    },
    success: function(result) {
      $("#test1").html(result);
      console.log('calling test1');
    }
  });

  $.ajax({
    url: 'config/db2.php',
    type: 'POST',
    data: {
      search: $(this).val()
    },
    success: function(result) {
      $("#test2").html(result);
      console.log('calling test2');
    }
  });
  setInterval(update, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

有什么帮助吗?我查了这个错误,但我找不到任何我能理解的东西。

问题是 $(this)。 Jquery 在找不到属性时会出现误导性错误消息,并且由于您正在引用 $(this),我认为它指的是您的文档对象,考虑到文档对象没有值,它将无效属性。

为您的搜索输入输入一个 ID,例如 'search_box' 然后

$(document).ready(function update() {
  $.ajax({
    url: 'config/db.php',
    type: 'POST',
    data: {
      search: $("#search_term").val()
    },
    success: function(result) {
      $("#test1").html(result);
      console.log('calling test1');
    }
  });

  $.ajax({
    url: 'config/db2.php',
    type: 'POST',
    data: {
      search: $("#search_term").val()
    },
    success: function(result) {
      $("#test2").html(result);
      console.log('calling test2');
    }
  });
  setInterval(update, 1000);
});