【发布时间】: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' => $row_set))的内容,以获取由您在 javascript 中检查的“内容”索引索引的数组。 -
那个确实把事情搞砸了;)没有结果列表......并且“标签”为空......
标签: jquery autocomplete