【问题标题】:Trying to get id and value with typeahead.js and php and Ajax尝试使用 typeahead.js 和 php 和 Ajax 获取 id 和 value
【发布时间】:2019-05-29 19:39:38
【问题描述】:

我正在尝试从数据库中获取国家/地区的 id 和名称并进行自动完成,这将获取国家/地区的 id 以便在 db 中进一步搜索。但是当我只想获取名称时它可以完美地工作但是当我也想获得 id 没有任何效果。非常感谢您的帮助。

fetch.php

<?php 
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
echo 'Connect Error (' . $conn->connect_errno . ') '
    . $conn->connect_error;
}
// $conn;
$request = mysqli_real_escape_string($conn,$_POST["query"]);
$sql = "SELECT * FROM countries where name like '".$request."%' ";
$result = $conn->query($sql);

$data = array();

if ($result->num_rows > 0) {
 // output data of each row
 while($row = $result->fetch_assoc()) {
      $data[] = array('name' => $row["name"] , 'id'=> $row["id"]);
 }
echo json_encode($data);
} 
?>

index.php

<script>
$(document).ready(function(){
 
 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data){
     result($.map(data, function(item){
      return {
          id:item.id,
          name:item.name
      }
     }));
    }
   })
  }
  select: function (event,ui){
     $(this).val(ui.item.name);
     $('#idc').val(ui.item.id);
     return false;
     }
 });
 
});
</script>
 <form action="" method="post">
   <input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />
   <input type="hidden" name="idc" value="" id="idc">
   <input type="submit" value="submit">
     </form>

上面的脚本不起作用,因为我也在尝试获取 id。 但下面的脚本有效,因为它只显示国家/地区的名称。

<script>
$(document).ready(function(){
 
 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data){
     result($.map(data, function(item){
      return {
          id:item.id,
          name:item.name
      }
     }));
    }
   })
  }
 });
 
});
</script>

请注意,对于上面的脚本,我只是删除了 select:function(event,ui) 并且没有其他任何更改。所以我想这就是问题所在。因为即使我没有更改退货或其他任何内容,它仍然显示名称。 非常感谢您的帮助。

【问题讨论】:

    标签: php jquery autocomplete typeahead.js


    【解决方案1】:

    我在同一天解决了它,但我太忙了,无法在这里更新结果。 我的错误是我将 jquery autocomplete 和 typeahead 结合在一起。 对于我想做的 jquery 自动完成功能已经绰绰有余了,这是它的代码

    $('#placeautocomplete').autocomplete({
              source: "fetch.php",
              select: function (event,ui){
                   $(this).val(ui.item.value)
                   $('#placeidautoc').val(ui.item.id);
              },
              minLength: 2,
              autoFocus :true,
    
         });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多