【问题标题】:using setInterval in ajax function returns 'toLowerCase' error [closed]在ajax函数中使用setInterval返回'toLowerCase'错误[关闭]
【发布时间】:2020-10-14 21:02:10
【问题描述】:

我尝试每隔 x 秒调用一次此函数,但它返回此错误:

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>

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

【问题讨论】:

  • 您发布的代码没有toLowerCase
  • 在调用 val() 时,你想用 this 引用什么?
  • @Phix 是的,但那执行sn-p时在控制台中记录的错误。
  • 对,但没有可重现的例子谁知道。
  • 您还在寻找@Phix 的更多可重现示例吗?执行问题中的代码会重现该错误。

标签: javascript jquery ajax setinterval


【解决方案1】:

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

给你的搜索输入一个像“search_box”这样的ID,然后

$(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);
});

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2014-10-25
    • 2012-01-08
    相关资源
    最近更新 更多