【问题标题】:Bootstrap Typeahead with AJAX source (not working)Bootstrap Typeahead 与 AJAX 源(不工作)
【发布时间】:2013-12-26 06:23:29
【问题描述】:

我正在尝试使用带有 typeahead.js 的 bootstrap v3.0.0 实现搜索栏下拉菜单。 我的搜索栏将采用学生的名字和姓氏。我正在使用一个 MYSQL 数据库,它由一个名为 practice 的表组成,其中 afirstname、alastname、aid 作为列。搜索栏不仅应包含下拉列表中的名字和姓氏,还应在第二行中包含与其关联的 id。我已经阅读了 typeahead.js 页面上的所有示例,但我无法通过 ajax 调用来做到这一点。

下面是我的index.php

JS

的代码
<script type="text/javascript">

      $(document).ready(function() {
        $('.cr.typeahead').typeahead({
          source:  header: '<h3>Select</h3>',
          name: 'accounts',

          source: function (query, process) {
                return $.getJSON(
                    'localhost/resultly/source.php',
                    { query: query },
                    function (data) {
                        return process(data);
                    });
        });
      });
    </script>

HTML:

     <body>
     <div class="container">

     <br/><br/>

    <input type="text" name="query" class="form-control cr typeahead" id="firstname" />

    <br/><br/>



    </div>
    </body>

source.php 的代码:这应该以 json 字符串或对象的形式从我的数据库中返回名字和姓氏?

<?php 
    $query = $_POST['query'];

    try {


        $conn = new PDO('mysql:host=localhost;dbname=practice','root','');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


        $stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
        $stmt->execute();





    } 

    catch (PDOException $e) {
        echo 'ERROR:' . $e->getMessage();
    }



    foreach ($stmt as $row) {
            $afirstname[] = $row['afirstname'];
            $alastname[] = $row['alastname'];


    }

    echo json_encode($afirstname);
    echo json_encode($alastname);


 ?>

结果: http://oi41.tinypic.com/50moi1.jpg

什么都没有出现。我试过添加prefetch:

 prefetch: {
                url: 'localhost/resultly/source.php',
                filter: function(data) {
                r1 = [];
                for (var i = 0;  i < data.length;  i++) {
                r1.push({
                value: data[i].afirstname,
                tokens: [data[i].afirstname, data[i]alastname],
                afirstname: data[i].afirstname,
                alastname: data[i].alastname,
                template: '<p>{{afirstname}} - {{alastname}}</p>',
                });
            }
            return r1;
        }
    }

请提供我可以参考的解决方案或示例。

更新:

source.php 应该返回一个 json 编码数据的列表。我通过查看 source.pho 创建的输出进行了调试。我做错的是每当我应该输入一个网址时,我做了localhost/source.php 而不仅仅是source.php

Bass Jobsen 提供的解决方案有效,现在我遇到了另一个问题。

我正在使用 if(isset($_POST['query'])) { $q_uery = $_POST['query']; $query = ucfirst(strtolower($q_uery))};

获取用户的数据并将其用于搜索逻辑 $stmt = $conn-&gt;prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");

更新后的source.php为http://pastebin.com/T9Q4m10g

我在这一行收到一条错误消息 Notice: Undefined variable: stmt I guess the $query is not being initialized。我怎样才能让它工作。谢谢。

更新 3

我使用了 prefetch: 而不是 'remote:' 来完成所有的匹配。

【问题讨论】:

    标签: ajax twitter-bootstrap-3 bootstrap-typeahead typeahead typeahead.js


    【解决方案1】:

    它对我有用。请按照以下步骤操作。

    请在Js下方添加并给出适当的参考。

    bootstrap3-typeahead

    --- Ajax 调用----

    $("#cityId").keyup(function () {
        var al = $(this).val();
        $('#cityId').typeahead({
            source: function (valuequery, process) {
                var states = [];
                return $.ajax({
                    url: http://localhost:4000/GetcityList,
                    type: 'POST',
                    data: { valueType: "", valueFilter: valuequery },
                    dataType: 'JSON',
                    success: function (result) {
                        var resultList = result.map(function (item) {
                            states.push({
                                "name": item.Value,
                                "value": item.Key
                            });
                        });
    
                        return process(states);
                    }
                });
            },
        });
    });
    

    ---- Cs代码---

    public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
            {
                List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
                return Json(returnValue);
            }
    

    Bootstrap 字体的自动提示将只接受“名称”和“值”,因此相应地创建响应

    【讨论】:

      【解决方案2】:

      你的回报不正确:

      echo json_encode($afirstname);
      echo json_encode($alastname);
      

      参见例如Twitter TypeAhead.js not updating input

      试试echo json_encode((object)$stmt);,见:typeahead.js search from beginng

      更新

      我试过 echo json_encode((object)$stmt);还是不行。

      您是否使用任何类型的调试?有什么作用? source.php 返回?尝试按照以下步骤操作 typeahead.js search from beginng 没有过滤器。

      html:

      <div class="demo">
        <input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
      </div>
      

      javascript:

      $('.typeahead').typeahead({                                
              remote: 'http://testdrive/source.php?q=%QUERY',
              limit: 10                                                                   
              });
      

      php (source.php):

      <?php
      $people = array();
      $people[] = array("lastname"=>"Inaw",
          "firstname"=>"Dsajhjkdsa");
      $people[] = array("lastname"=>"Dsahjk",
          "firstname"=>"YYYsgbm");
      $people[] = array("lastname"=>"Dasjhdsjka",
          "firstname"=>"JHJKGJ");
      
      $datums = array();  
      foreach($people as $human)
      {
          $datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
      }     
      
      echo json_encode((object)$datums);
      

      这应该可以工作

      更新2

      谢谢,成功了。如何显示 2 个或更多“值”?

      在 source.php 中为您的数据添加一些值:

      foreach($people as $human)
      {
          $datums[]=(object)array
          (
              'value'=>$human['firstname'],
              'tokens'=>array($human['firstname'],$human['lastname']),
              'firstname'=>$human['firstname'],
              'lastname'=>$human['lastname']
          );
      }
      

      firstnamelastname 现在是您在模板中使用的字段

      将模板和模板引擎添加到您的 javascript 声明中:

      $('.typeahead').typeahead({                                
              remote: 'http://testdrive/source.php?q=%QUERY',
              limit: 10,
                template: [ 
                '<p>{{firstname}} - {{lastname}}</p>'    
                ].join(''),
                engine: Hogan 
      
              });
      

      以上使用https://github.com/twitter/hogan.js。您必须通过 javascript 包含模板引擎,例如:

      &lt;script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"&gt;&lt;/script&gt;

      【讨论】:

      • 我试过echo json_encode((object)$stmt);还是不行。
      • 谢谢,它成功了。如何显示 2 个或更多“值”?我试过了:$datums[]=(object)array('value'=&gt;array($human['firstname'],$human['lastname']),'tokens'=&gt;array($human['firstname'],$human['lastname'])); 没用。我需要使用模板吗:?
      • 成功了,有没有我可以听我的输入字段?然后使用 LIKE the users data 将该值放入我的 WHERE 子句中。我尝试了 $_POST[],但这并不像更新问题中提到的那样起作用。
      • 使用 $_GET 而不是 $_POST
      • 我在一个带有 method="post" 的表单中有输入字段,并且操作设置为不同的 php 文件。即使我使用 $_GET 如何动态获取输入字段的 value 属性?我的意思是价值=“用户输入”。我几乎被困在最后一部分了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多