jQuery ui 文档的关键在于找到正确的页面。
您需要的是 Remote jsonp datasource 示例。
我在remote datasource 示例上浪费了很多时间(我什至无法运行),因为我害怕“p”...
所以here is my version,稍微增强了一个动态加载自动完成下拉列表的示例。
我希望它能帮助很多人。
有趣的是,我没有像 jQuery 文档建议的那样使用 jsonp。
它会在控制台中产生一个奇怪的不清楚的错误:
Error: jQuery112409377035747123055_1476875409950 was not called(…)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<style>
.ui-autocomplete-loading {
background: white url("ajax-loader.gif") right center no-repeat;
}
.ui-widget{
width:500px;
}
.ui-front{
width:10em;
background-color:#bebebe;
}
#log{
height: 200px;
width: 500px;
overflow: auto;
}
#noResult{
display:none;
color:red;
padding-left:1em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
function log( message ){
$( "<div>" ).text( message ).appendTo( "#log" );
$("#UScities").blur();
}
$( "#UScities" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
data: {keyword:request.term},
dataType: 'json', // DON'T use jsonp !
cache: false,
success: function(data){
console.log(data);
// Even on success, it may have no results...
if(typeof(data[0])!="undefined"){
// Remove the no result error in case it's displayed
$("#noResult").css("display","none");
// For fun, count it!
var count = 0;
while (data[count]) {
console.log(data[count]);
count++;
}
}else{
count = "NO";
// Display the no result error
$("#noResult").css("display","inline");
}
console.log(count+" RESULTS");
// Pass the data to the dropdown!
response(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
},
minLength: 4,
select: function( event, ui ) {
log( ui.item.value );
}
});
// Show results on input focus
$("#UScities").on("focus",function(){
$("#ui-id-1").css("display","block");
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="UScities">USA cities: </label>
<input type="text" id="UScities"><span id="noResult">No Result</span><br>
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
<div id="log" class="ui-widget-content"></div>
</div>
</body>
</html>
我在控制台中添加了结果计数(可用于触发某些事情)并向用户添加“NO RESULT”消息,因为关键字搜索可能没有结果。
现在,jQuery 文档中非常缺乏的是如何生成 json 输出。
<?php
if (!isset($_GET['keyword'])) {
// Do nothing if no keyword!
die();
}
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[Database Name];host=localhost';
$user = '[Database User]';
$password = '[UserPassword]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
// Getting the keyword and add % to get data that begins with it.
$keyword = $_GET['keyword'] . '%';
// If you want the keyword to be "contained" in the data, use (uncomment it):
//$keyword = '%' . $_GET['keyword'] . '%';
// Query.
$query = "SELECT city FROM SO_USAzipcodes WHERE city LIKE ? GROUP BY city limit 30";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $keyword);
// Executing.
$stmt->execute();
// If SQL error...
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die();
}
// Fetching.
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
// This is sending the json to autocomplete.
echo json_encode( $data );
?>
如果您在此文件中有语法错误...
或者如果由于 DB 连接或 SQL 语法错误而出现错误...
你会在控制台中得到这样的东西:
SyntaxError: Unexpected token < in JSON at position 0(…)
主页上什么也没有发生,但旋转的.gif 一直在转动。顺便说一句,我刚刚发现了这个值得一看的loading gif generator。 ;)