我正在尝试 jQuery 的自动完成小部件,并且有点碰壁。将不胜感激一些输入/指导。
本质上,我有一个表单,有人将在其中输入一个人的名字……然后jQuery 将查询数据库并建议匹配项。该表单有两个字段需要从 JSON 数据中填充 - 名称字段和隐藏的 ID 字段。到目前为止,我可以让它只给出建议并在选择时填写名称字段,但没有运气让它更新隐藏的 ID 字段。我知道我必须从 jQuery 代码中遗漏一些关键,但还没有弄清楚。我曾尝试使用“选择”事件设置值,但没有运气。
这是相关的表格代码:
<div id="formblock" class="stack">
<label>Project POC: <span class="error" name="proj_poc_error" id="proj_desc_error">This field is required.</span></label>
<input type="text" name="proj_poc" id="proj_poc">
<input type="hidden" name="proj_poc_id" id="proj_poc_id" value="NOT SET">
</div>
这是相关的jQuery代码:
$(function() {
$( "#proj_poc" ).autocomplete({
source: function(request, response){
$.getJSON("/includes/AJAX/GetContactNames.php?callback=?", request, function(data){
var suggestions = [];
$.each(data, function(i, val){
suggestions.push(val.contacts);
});
response(suggestions);
});
},
minLength: 2,
select: function( event, ui ){
//Should display user ID a
alert(ui.item.id + ui.item.contacts);
}
});
});
这是来自 GetContactNames.php 的相关 PHP
//Initiate the session
session_start();
//Load custom classes
include_once ('../../ops.inc.php');
//Get the search term from GET
$param = $_GET['term'];
//Create new dblink class and connect to db
$uplink = new dblink();
$uplink->connect();
//Create new dbcontrol class
$control = new dbcontrol();
//Set the query to select ID and CONCAT'd NAME from Contact Table
$control->query = "SELECT `id`, CONCAT_WS(\" \",`firstname`,`lastname`) AS 'contacts' FROM `addressbook` WHERE `firstname` REGEXP '^$param'";
//Execute the query
$control->execute();
//Set an iterator value to 0
$i = 0;
//Get the results into array, then iterate.
while($row = $control->toAssocArray()){
foreach($row as $column=>$value){
$results[$i][$column] = $value;
}
$i++;
}
//Set the response string and encode for json
$response = $_GET['callback']."(".json_encode($results).")";
//Display the response string
echo $response;
//Disconnect from the database
$uplink->disconnect();
//Destroy classes
unset($uplink, $control);
GetContactNames.php 结果的输出如下所示:
([{"id":"1","name":"Santa Clause"},{"id":"2","name":"Joe Blow"}])
有什么建议么?