JQuery UI自动完成与json和ajax
问题描述:
我见过很多问题处理通过JSON传递带标签和值属性的数组,但传递字符串并不多。我的问题是,我似乎无法让我的自动填充功能填满。我跑了转储功能,我得到通过JSON传递给自动完成这些样本值:JQuery UI自动完成与json和ajax
0: 23456
1: 21111
2: 25698
下面是一些代码:
$("#auto_id").autocomplete({
source: function(request,response) {
$.ajax ({
url: "fill_id.php",
data: {term: request.term},
dataType: "json",
success: function(data) {
//what goes here?
}
}) }
});
这里是fill_id.php:
$param = $_GET['term'];
$options = array();
$db = new SQLite3('database/main.db');
$results = $db->query("SELECT distinct(turninId) FROM main WHERE turninid LIKE '".$param."%'");
while ($row_id = $results->fetchArray()) {
$options[] = $row_id['turninId'];
}
echo json_encode($options);
我自动填充保持空白。我如何更改我的JSON数组来填充它?或者我在ajax成功函数中包含什么?
答
你能坚持很符合的jQuery UI的自动完成功能的远程演示:http://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html
为了让您的成绩进入自动完成的列表中,你需要把一个对象与标签和价值的响应参数(其实际上是一个函数)你的Ajax成功函数中:
source: function(request, response) {
$.ajax({
url: "fill_id.php",
data: {term: request.term},
dataType: "json",
success: function(data) {
response($.map(data.myData, function(item) {
return {
label: item.title,
value: item.turninId
}
}));
}
});
}
但这如果修改侑fill_id.php有点只会工作:
// escape your parameters to prevent sql injection
$param = mysql_real_escape_string($_GET['term']);
$options = array();
// fetch a title for a better user experience maybe..
$db = new SQLite3('database/main.db');
$results = $db->query("SELECT distinct(turninId), title FROM main WHERE turninid LIKE '".$param."%'");
while ($row_id = $results->fetchArray()) {
// more structure in data allows an easier processing
$options['myData'][] = array(
'turninId' => $row_id['turninId'],
'title' => $row_id['title']
);
}
// modify your http header to json, to help browsers to naturally handle your response with
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($options);
当然,如果您的表格中没有标题或任何内容,您也可以保留原样,并在成功回调中重复该ID。重要的是,你填写你response
功能自动完成与价值/项目对:
// this will probably work without modifying your php file at all:
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
编辑: 更新的参考链接到新的jQuery UI的自动完成界面
我还以为你也可以填写只有字符串的数组? – hereiam 2012-08-07 20:49:52
另外,我的http的修改是否必要?你能解释一下吗? – hereiam 2012-08-07 21:01:54
感谢您的帮助!完美工作! – hereiam 2012-08-07 21:08:09