我想通过 jquery 从服务器加载整个源数据,但在页面加载时只加载一次。我想将它存储在一个变量中。jquery 部分可以工作,但输入不会自动完成。它什么也不做。它只有在源代码写成 source: ["blablabla","dadadada"] 时才有效。
这是我的 Javascript 代码:
var datasource; // this is the variable where my source will be stored
$.post("typeahead.php",
{
query: 'query' // 'query' has no meaning ;)
},
function(data) { // data looks like ["asd","fds"] thanks to json_encode on the server side
datasource = data;
});
$('#searchInput').typeahead( {
source: datasource
});
服务器端php代码:
/* connect to the db */
$con = mysql_connect("localhost","fahrschulesql1","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select Database
$db_selected = mysql_select_db("fahrschulesql1", $con);
if (!$db_selected) {
die ("Select DB error: " . mysql_error());
}
$query = "SELECT Vorname, Nachname FROM Benutzer b, Fahrlehrer f WHERE b.BenutzerID = f.BenutzerID";
$result = mysql_query($query) or die ("MySQL-Error: " . mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = $row["Vorname"] . " " . $row["Nachname"];
}
echo json_encode($array);
mysql_close($con);
我究竟做错了什么?