问题描述
我想通过jquery从服务器上加载整个源数据,但仅在页面加载上加载一次.我想将其存储在变量中. jQuery部分有效,但输入不会自动完成.它什么也没做.仅当源代码写成类似源代码时才有效:["blablabla","dadadada"].
I want to load the whole source data via jquery from the server but only once on pageload. I want to store it in a variable. The jquery part works but the input does not autocomplete. It does nothing. It works only if the source is written like source: ["blablabla","dadadada"].
这是我的Javascript代码:
This is my Javascript Code:
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);
我在做什么错了?
推荐答案
通过分配新数组,您将丢失对数组datasource
的引用.您将需要操纵该数组以避免丢失对该数组的引用.
You are losing the reference to the array datasource
by assigning a new array. You will need to manipulate the array to avoid losing the reference to it.
var datasource = [];
$.post("typeahead.php", {
query: 'query'
}, function(data) {
/* Add the responses to the datasource, don't mess up the reference */
[].push.apply(datasource, data);
});
$('#searchInput').typeahead({
source: datasource
});
另一个选项是缓存响应.我个人比以前的方法更喜欢这种方法.
Another option is caching the response. I personally prefer this method over the previous one.
您可以在发送第一个请求后使用process
回调并缓存数据.从此开始,使用缓存的数据.
You can use the process
callback after sending the first request and cache the data. Onwards, use the cached data.
var cachedsource = (function(){
var datasource = null;
return function(query, process){
if(datasource !== null) {
/* use cached data */
return datasource;
} else {
$.post("typeahead.php", {
query: 'query'
}, function(data) {
/* cache data */
datasource = data;
process(datasource);
});
}
};
})();
$('#searchInput').typeahead({
source: cachedsource
});
PHP返回不正确的Content-Type
.尝试使用$.ajax
代替$.post
.
PHP is returning incorrect Content-Type
. Try $.ajax
instead of $.post
.
$.ajax({
url: "typeahead.php",
data: {
query: 'query'
},
success: function(data) {
/* cache data */
datasource = data;
process(datasource);
},
dataType: "json"
});
注意dataType
设置为json
.
您还可以使用 header()
Content-Type >.
header('Content-Type: application/json');
echo json_encode($array);
这篇关于Bootstrap typeahead自动完成,源仅在页面加载时加载一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!