php - 如何在可选列表中查看实时搜索结果?

标签 php jquery html mysql css

我是 jQuery 的新手,所以希望我的问题很简单:

我用 PHP 和 mySQL 编写了一个简单的 jQuery 实时搜索程序,它运行良好。

我的问题是:我想在列表中显示搜索结果,然后选择要写入文本框中的显示结果之一。

HTML代码:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<script type="text/javascript">
$(function (){
$(document).on('keyup', '[name="state"]', function() {
     var partialState = $(this).val();
     $.post("getStates.php",{partialState:partialState}, function(data){
        $("#results").html(data);
     });
});
});
</script>
</head>

<body>
   <input type = "text" name = "state" autocomplete = "off"/>
   <br>
   <div id = "results"> </div>
</body>

</html>

我的 php 代码:

<?php

  error_reporting(E_ALL);
  ini_set('display_errors', 1);

  $con = mysqli_connect("localhost", "root", "")
  or die("Failed to connect to the server: " . mysql_error());

  mysqli_select_db($con, "airlines")
  or die("Failed to connect to the database: " . mysql_error());

  $partialStates = strtoupper($_POST['partialState']);

  if(!$partialStates)
  {
     echo "";
  }
  else
  {
     $states = mysqli_query($con,"select distinct source from flights where source like '%$partialStates%'") or die(mysql_error());

    while($row = mysqli_fetch_array($states))
    {
       echo "<div>" . $row['source'] . "</div>";
    }
  }

?>

有什么帮助吗?

最佳答案

首先查看准备好的语句以防止在 where source like '%$partialStates%' 处进行 sql 注入(inject)。

然后,不返回 HTML,

while($row = mysqli_fetch_array($states))
{
echo "<div>" . $row['source'] . "</div>";
}

使用 JSON 会更方便:

$sources = array();
while($row = mysqli_fetch_array($states)) {
    $sources[] = $row['source'];
}
header('Content-Type: application/json');
echo json_encode($sources);

选择第一个返回的状态,并更新输入框。改变

$.post("getStates.php",{partialState:partialState}, function(data){
    $("#results").html(data);
});

$.getJSON( "getStates.php", { partialState: partialState }, function( states ) {
    $('input').val(states[0]);
});

关于php - 如何在可选列表中查看实时搜索结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185953/

相关文章:

javascript - Jquery 验证器不工作

html - 不用javascript使div填充浏览器窗口的剩余高度

javascript - 如何使用javascript或jQuery按顺序更改 "["和 "]"?

php - 如何获取 gearman 中特定类型的排队作业数?

php email - 如何避免邮件在垃圾邮件箱中结束

php - 从mysql获取两个时间戳之间的数据

javascript - "Origin null is not allowed by Access-Control-Allow-Origin."使用 jQuery 调用 Web 服务时出错

javascript - 如何将图像填充为链接,并将其作为 JSON 对象存储在数组中?

html - 我想在透明背景上制作不透明文本

php - 重新加载页面后 $_SESSION 为空