我有这个代码
Function.js 文件
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( ".country_suggestion" ).bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
type: "POST",
url: "/suggestion.php",
data:'term='+request.term,
success: function(r){
return r;
//response(r);
},
error: function (request, status, error) {
}
});
// delegate back to autocomplete, but extract the last term
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
在 PHP 文件中
<?php
include('inc/safePDO.class.php');
include('inc/config.php');
$dbh = new
SafePDO('mysql:host='.$db['host'].';
dbname='.$db['name'].';charset=UTF8', $db['user'], $db['password']);
$term = $_POST['term'];
$list = $dbh->prepare("SELECT * FROM ((
SELECT `id`, `label` as name, CHAR_LENGTH(`label`) as name_length FROM `country`
WHERE `label` LIKE :name
) UNION (
SELECT `id`, `label` as name, CHAR_LENGTH(`label`) as name_length FROM `countryregion`
WHERE `label` LIKE :name
)) as t
GROUP BY `name`
ORDER BY name_length ASC
LIMIT 0, 10");
$list->execute(array(':name' => "%{$term}%"));
$country_list = $list->fetchAll(PDO::FETCH_OBJ);
$country = array();
foreach($country_list as $country_region_list) {
$country[] = $country_region_list->name;
}
//print_r($country_list);
echo json_encode($country);
我尝试了大部分方法,通过谷歌搜索但没有得到结果。
我正在以排序的形式从数据库获取数据,但唯一不起作用的是弹出窗口..aucomplete 弹出窗口未显示...
如果我在ajax成功时打印警报,它会显示短路数据,但之后我不知道该怎么办......任何帮助将不胜感激。
最佳答案
PDO 不允许使用多个占位符,请参阅 this question
您可以更改代码,重命名参数而不重复:
$list = $dbh->prepare("SELECT * FROM ((
SELECT `id`, `label` as name, CHAR_LENGTH(`label`) as name_length FROM `country`
WHERE `label` LIKE :name1
) UNION (
SELECT `id`, `label` as name, CHAR_LENGTH(`label`) as name_length FROM `countryregion`
WHERE `label` LIKE :name2
)) as t
GROUP BY `name`
ORDER BY name_length ASC
LIMIT 0, 10");
$list->execute(array(':name1' => "%{$term}%",':name2' => "%{$term}%"));
关于javascript - 为什么我的 Jquery Autocomplete 无法处理 Mysql 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203783/