【发布时间】:2012-06-17 17:09:52
【问题描述】:
我想做一个搜索框,你可以在其中搜索数据库中的记录。
search.php 看起来像这样:
<?php
// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');
$nameser = $_GET['term'];
$names = array();
$result = mysql_query("SELECT name,customerid FROM customers WHERE name LIKE '%".$nameser."%' ORDER BY name ASC");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['customerid'];
$row_array['value'] = htmlentities($row['name']);
array_push($names,$row_array);
}
echo json_encode($names);
?>
Javascript 部分如下所示:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
但是,这会产生错误:
ReferenceError: item is not defined
我想要发生的是,当我单击结果列表中的某些内容时,我会被重定向到 url
customers.php?action=view&cid={CustomerID}
有人有想法吗?
编辑:
正确有效的 Javascript 代码:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + ui.item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
【问题讨论】:
-
第5行,js:什么是item?全局变量?
-
@Alex:我其实不知道——但它在第 13 行有效。脚本是从这里的其他帖子中复制/粘贴的。
-
第 13 行
item是传递给函数 _renderItem 的参数,所以没关系。请在select事件之前发布链接的样子。 -
并且还尝试查看
ui对象,也许它包含选定的项目 -
@Alex:链接在列表中看起来正确。我不明白应该如何查看 ui 对象?
标签: php javascript jquery jquery-ui jquery-ui-autocomplete