【问题标题】:Bootstrap typeahead autocompletion with the source loaded only once on pageloadBootstrap 预输入自动完成,源在页面加载时仅加载一次
【发布时间】:2012-12-26 23:43:54
【问题描述】:

我想通过 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);

我做错了什么?

【问题讨论】:

  • 你在使用 Twitter Bootstrap v2.1 吗?
  • 我刚刚更新了我的答案。随意尝试

标签: javascript jquery twitter-bootstrap bootstrap-typeahead


【解决方案1】:

通过分配一个新数组,您正在丢失对数组 datasource 的引用。您需要操作数组以避免丢失对它的引用。

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
});

See it here.


另一个选项是缓存响应。我个人更喜欢这种方法而不是前一种方法。

您可以在发送第一个请求后使用process 回调并缓存数据。之后,使用缓存的数据。

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
});

See it here.


PHP 返回不正确的Content-Type。试试$.ajax 而不是$.post

$.ajax({
  url: "typeahead.php", 
  data: {
    query: 'query'
  },
  success: function(data) {
    /* cache data */
    datasource = data;
    process(datasource);
  },
  dataType: "json"
});

注意dataType 设置为json

您还可以在 PHP 中使用 header() 设置正确的 Content-Type

header('Content-Type: application/json');
echo json_encode($array);

【讨论】:

  • 我使用了你的缓存版本,它似乎运行良好,但这就是我得到的:abload.de/img/typeahead4wje6.jpg
  • @XHotSniperX,用你的服务器端脚本更新你的问题。因为,这里列出的两个选项都有效
  • @XHotSniperX,你能在$.post的成功句柄中记录data的内容吗?恐怕这个问题可能与预输入脚本无关
  • 您的第一个方法给出了错误:未捕获的 TypeError: Function.prototype.apply: Arguments list has wrong type。回调函数中的 alert(data) 发布:["Marc Tarnutzer","Michael Schumacher"]。正是我想要的。
  • @XHotSniperX,好吧,您的来源不匹配。当假设只有两个时,屏幕截图中有三个结果。您在某处被覆盖。那么最好粘贴你的完整代码,没有sn-ps。这花费了太多时间
【解决方案2】:

你的 html 代码在哪里?

你在用这个吗:

<input id="searchInput" type="text" data-provide="typeahead">

?

然后确保您的回调在 firebug 中正常并返回数据,因为您没有在此处指定任何 url,例如:

$.post("typeahead.php",

然后确保你在 document.ready 中运行你的 js

$(document).ready(function(){

//do my js
});

也可以试试:

console.log(datasource); 在将该 var 传递给引导插件之前

一定要试试这个:

$(function(){

$.post("typeahead.php",
  {
    query: 'query'       // 'query' has no meaning ;)
  }, 
  function(data) {       // data looks like ["asd","fds"] thanks to json_encode on the server side
    $('#searchInput').typeahead( {
  source: data
});
});

});

【讨论】:

  • 是的,我正在使用这个
  • 是的,在 Chrome 工具中我可以看到响应是:["blablabla","blablabla"]
  • 有趣,在输入中输入什么?控制台中的任何错误? :P
  • 不,没有错误。它不会自动完成。它就像一个普通的输入文本输入字段。它仅在我写“source:[“asdfasd”,“sdfsadh”...]时才有效。我也这样做了lukeschreur.com/posts/…,但它无法正常工作。我必须将JSON转换为数组吗?
  • 不,我认为您应该尝试转储数据以检查是否将其返回到插件中,请尝试 console.log(datasource); 在请求完成之前将其传递给插件,你运行document.ready里面的所有js了吗?
猜你喜欢
  • 2016-08-14
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 2019-01-06
  • 1970-01-01
  • 2014-08-08
相关资源
最近更新 更多