【问题标题】:jQuery Autocomplete response return: Cannot read property 'length' of nulljQuery 自动完成响应返回:无法读取 null 的属性“长度”
【发布时间】:2017-01-10 10:19:47
【问题描述】:

我正在尝试创建一个函数,当“自动完成”未找到任何结果时将显示一个按钮。

PHP

echo json_encode($row_set);

JS

$( '#objNr' ).autocomplete({
    source: 'php/v.php',
    minLength: 2,
    response: function(event, ui) {
        // ui.content is the array that's about to be sent to the response callback.
        if (ui.content.length === 0) {
            $('#newTableBtn').removeClass('hidden');
        } else {
            $("#newTableBtn").addClass('hidden');
        }
    },
    error: function(err){
        console.log(err);
    }
});

搜索工作正常。我得到结果。但是当我没有结果时,我会收到以下消息:

未捕获的类型错误:无法读取 null 的属性“长度” 在 HTMLInputElement.response

怎么了?

更新 PHP

 while ($row = $stmt->fetch()){
    $row['id'] = $i+1;
    $row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data  

更新 JS

response: function(event, ui) {
        if (ui.content != null && ui.content.length < 1) {
            $('#newTableBtn').removeClass('hidden');
            console.log('if')
        } else {
            $("#newTableBtn").addClass('hidden');
            console.log('else')
        }
    },

这个清除了错误信息。但是 else 的情况不管它是否是结果都会消失...

【问题讨论】:

  • 很高兴看到$row_set 是如何创建的。也许这只是该变量内容的问题,没有正确的键
  • 如果您将console.log(ui) 放在IF 之前,您应该了解您从服务器有效接收的内容。我想问题出在变量创建上;您有一个 json 行数组,但该数组中没有 content
  • 对象内容:Array[153] [0 … 99] 0:对象 id:1 标签:“22133-01”值:“22133-01”
  • 所以,我想回到 php 文件中,您可以编写类似 json_encode(array('content' =&gt; $row_set)) 的内容,以获取由您在 javascript 中检查的“内容”索引索引的数组。
  • 那个确实把事情搞砸了;)没有结果列表......并且“标签”为空......

标签: jquery autocomplete


【解决方案1】:

在与@björn-c 进行了长时间而愉快的讨论后,我们发现问题在于在获取结果之前没有初始化数组$row_set。这样, json_encode 将对结果进行编码 null 并且自动完成会抛出错误。

所以,解决办法是放

$row_set = array();

在从数据库中获取结果的while循环中使用它之前。

然后瞧! :)

【讨论】:

    【解决方案2】:

    试试这个:

    if (ui.content != null && ui.content.length < 1) {
      $('#newTableBtn').removeClass('hidden');
    } else {
      $("#newTableBtn").addClass('hidden');
    }
    

    如果ui.content 为空,如果您试图获取它的长度属性,它将引发异常。确保不是。

    【讨论】:

    • 我确实在 else 子句中输入了:console.log('else').. 并且当我得到结果和没有结果时都会打印 else ......但是错误消失了;)
    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2023-03-11
    • 2013-03-21
    • 2015-04-06
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    相关资源
    最近更新 更多