php – jQuery UI自动填充json和ajax
发布时间:2020-12-13 16:02:39 所属栏目:PHP教程 来源:网络整理
导读:我看到很多关于通过 JSON传递带有标签和值属性的数组的问题,但传递字符串并不多.我的问题是,我似乎无法获得自动填充.我运行了一个转储功能,并将这些通过JSON传递的示例值传递给自动完成: 0: 234561: 211112: 25698 这里有一些代码: $("#auto_id").autocomp
|
我看到很多关于通过
JSON传递带有标签和值属性的数组的问题,但传递字符串并不多.我的问题是,我似乎无法获得自动填充.我运行了一个转储功能,并将这些通过JSON传递的示例值传递给自动完成:
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成功函数内放置一个带有标签和值的对象作为response参数(实际上是一个函数): source: function( request,response ) {
$.ajax({
url: "fill_id.php",success: function( data ) {
response( $.map( data.myData,function( item ) {
return {
label: item.title,value: item.turninId
}
}));
}
});
}
但是,只有在你修改yor 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.重要的是,您在自动填充中填充一个值/项对: // this will probably work without modifying your php file at all:
response( $.map( data,function( item ) {
return {
label: item,value: item
}
}));
编辑:更新了参考链接到新的jquery UI的自动完成ui (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
