我尝试创建一个功能,当"自动完成"
找不到结果时,将显示一个按钮。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);
}
});
搜索工作正常。我得到了结果。但是当我没有结果时,我收到了这样的信息:
未捕获的TypeError:无法读取属性'长度'为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')
}
},
这一个清除了错误信息..但是,无论是否结果,其他情况都会消失......
答案 0 :(得分:1)
试试这个:
if (ui.content != null && ui.content.length < 1) {
$('#newTableBtn').removeClass('hidden');
} else {
$("#newTableBtn").addClass('hidden');
}
如果ui.content
为null,则在尝试获取它的长度属性时会抛出异常。确保不是。
答案 1 :(得分:1)
经过与@björn-c的长时间讨论后,我们发现问题在于在获取结果之前没有使数组$row_set
初始化。这样,json_encode将对结果null
进行编码,自动完成将抛出错误。
所以,解决方法是放
$row_set = array();
在while循环中使用它之前从db。
获取结果和Voilà! :)