来自jQuery的我的自动完成插件第一次没有在文本框中使用一个字符。
如果我继续输入多个字符,那么自动完成将启动...
所以我期待第一个角色的结果,但没有得到任何东西..
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "#names" ).keyup(function() {
autocompleteNames();
});
});
function loadNames(){
//Gets the name
var nameSelected = $("#names").val();
var namesList = "";
$.ajax({
url: 'names.php',
type: "POST",
async: false,
data: { sport: nameSelected}
}).done(function(names){
namesList = names.split(',');
});
//Returns the javascript array of names.
return namesList;
}
function autocompleteNames(){
var names = loadNames();
$("#names").autocomplete({
source: names,
minLength: 1
});
}
</script>
</head>
<body>
Namn: <input type="text" id="names" name="names" />
</body>
</html>
这是我的names.php文件非常简单
<?php
$sport = $_POST["sport"];
//Defines the name array.
$names[0] = "Sam";
$names[1] = "Anna";
$names[2] = "Jens";
$names[3] = "Johanna";
$names[4] = "Emma";
$names[5] = "Mikael";
$names[6] = "Mattias";
$names[7] = "Sebastian";
$names[8] = "Johan";
$names[9] = "Mona";
$names[10] = "Lina";
$names[11] = "Linda";
$names[12] = "Ebba";
$names[13] = "Andreas";
$names[14] = "Marcus";
$names[15] = "Markus";
$names[16] = "Anders";
$names[17] = "Maria";
$names[18] = "Sandra";
$names[19] = "Jonatan";
$names[20] = "Jacob";
$names[21] = "Carolina";
$names[22] = "Tom";
$names[23] = "Tim";
$names[24] = "Zlatan";
$names[25] = "Emelie";
//Defines an empty variable that will return the javascript array.
$teams = generateAutocompleteArray($names);
//Returns the teams in the appropriate javascript array format.
echo $teams;
//Function converts PHP array a string where it can be split into an array easily.
function generateAutocompleteArray($namesArray){
$jsNamesArray = "";
$teamCount = count($namesArray);
for($i=0; $i<$teamCount; $i++){
$jsNamesArray.= $namesArray[$i].',';
}
//Removes the remaining comma so you don't get a blank autocomplete option.
$jsNamesArray = substr($jsNamesArray, 0, -1);
return $jsNamesArray;
}
?>
答案 0 :(得分:0)
我认为你不应该将自动完成构造函数绑定到输入文本的keyup事件。如果是这样,则每次用户键入内容时都会重新创建对象。此外,您将返回namesList,并且它仍然可以从ajax请求加载。您必须等待请求完成才能拥有namesList,请记住javascript是异步的。
基本上,你必须只构造一次autocomplte,并寻找自动完成参数(source)来指定你的数据是通过ajax加载的。看看这个:jQuery autocomplete with callback ajax json