gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:27:18 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com