AJAX:如何获得字段的标签和值不同?

时间:2017-08-24 21:44:15

标签: php mysql ajax

我有以下两个文件 如何让AJAX填充标签和值

例如,如果值是芝加哥,IL。如何在提交表格时将价值仅提升为芝加哥?

在该字段下面填充,例如,芝加哥,伊利诺伊州

<!DOCTYPE html>
<html>
 <head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center"></h2>
   <br /><br />
   <label>Search Country</label>
   <input type="text" name="city" id="city" class="form-control input-lg" autocomplete="off" placeholder="Type City Name" />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 $('#city').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"TypeaheadTest2.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }
   })
  }
 });

});
</script>

下面是文件TypeaheadTest2.php

<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
 SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";

$result = mysqli_query($connect, $query);

$data = array();

if(mysqli_num_rows($result) > 0)
{
 while($row = mysqli_fetch_assoc($result))
 {
  $data[] = $row['city'] . ' ' . $row['state'];
 }
 echo json_encode($data);
}

?>

1 个答案:

答案 0 :(得分:0)

如果我找到了你,你就会如此接近你的期望。

我看到你在服务器端连接城市和州名。但是你想在typeahead选项上只显示城市名称。

我建议您将城市名称和州名称作为PHP中对象的单独属性传递,然后在Javascript端使用它们。

以下是示例代码, PHP:

<?php
    $connect = mysqli_connect("localhost", "", "", "");
    $request = mysqli_real_escape_string($connect, $_POST["query"]);
    $query = "
        SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
    ";

    $result = mysqli_query($connect, $query);

    $data = array();

    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_assoc($result)){
            $data[] = array('city'=>$row['city'], 'state'=>$row['state']);
        }
        echo json_encode($data);
    }

?>

使用Javascript:

$(document).ready(function(){

    $('#city').typeahead({
        source: function(query, result) {
            $.ajax({
                url:"TypeaheadTest2.php",
                method:"POST",
                data:{query:query},
                dataType:"json",
                success:function(data) {
                    result($.map(data, function(item){
                        return item.city;
                    }));
                }
            });
        }
    });

});