我正在尝试使我的自动完成搜索工作,但是当我尝试从我的json数组中获取数据时它不起作用。我对此并不熟悉,但这就是我的代码的样子。我想我知道第一个文件是如何工作的但是我不明白我的“searchapi.php”是如何编写的。什么是$ .map?如果有人能解释的话会很棒:D谢谢你
index.php:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
#city { width: 15em; }
</style>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table(?), function( item ) {
return {
label: item.name,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
searchapi.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$value = @$_POST['name_startsWith'];
$data = ("select name from column where name LIKE '".$value."'");
$result = mysql_query($data);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
?>
答案 0 :(得分:3)
searchapi.php
文件纯粹根据自动完成功能发送的字符串(name_startsWith)查询数据库中的相似条目。
$ .map是一种jQuery方法,用于将“数组或对象中的所有项目转换为新的项目数组”。您可以在此处阅读:http://api.jquery.com/jQuery.map/