[英]Use Jquery and Ajax to create autocomplete/autosuggest list with JSON data retrieved from API using PHP
[英]PHP & jQuery - Create two different textfields with autocomplete having different lists of data retrieved from the database
我成功创建了一个具有自动完成功能的Customer文本字段,以显示以键入的文本开头的客户。
一个文本字段的index.php
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#customer" ).autocomplete({
source: "../phpfiles/search.php",
});
});
</script>
<div class="ui-widget">
<!-- action='./../customer_report_request' -->
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
</table>
</form>
</div>
<?php
//Display the list of customer details
if(isset($_POST['send_customer_request']))
{
include 'db.php'; //connection
$query = "SELECT * FROM customer WHERE Company_Name = '".$_POST['customer']."'";
$customer_result = $db->query($query);
$count_customer = $customer_result->num_rows;
if($count_customer>0)
{
echo"<div>";
echo "<table>";
echo"<tr>";
echo"<th>Company_Name</th>";
echo"<th>VAT_Registration</th>";
echo"<th>Contact_First_Name</th>";
echo"<th>Contact_Last_Name</th>";
echo"<th>Email</th>";
echo"</tr>";
while ($row = $customer_result->fetch_assoc())
{
echo"<tr>";
echo"<td>".$row['Company_Name']."</td>";
echo"<td>".$row['VAT_Registration']."</td>";
echo"<td>".$row['Contact_First_Name']."</td>";
echo"<td>".$row['Contact_Last_Name']."</td>";
echo"<td>".$row['Email']."</td>";
echo"</tr>";
}
echo "</table>";
echo"</div>";
}
$db->close();
}
?>
Search.php的一个文本字段
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from customer table
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc()) {
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
?>
问题是我想使用一个搜索php文件来满足其他查询。 例如:
index.php和search.php都经过修改以实现此目的。
index.php中的修改部分
定义了一个jQuery变量component_name。 在更改 index.php文件时,客户texfield将使用POST方法将变量发送到search.php文件,以便可以对其进行标识并用于查询目的。
联系人文本字段可以是index.php文件中的相同形式,也可以是另一个php文件中的形式。
<script>
$(function() {
$( "#customer" ).autocomplete({
var component_name= "customer";
source: "../phpfiles/search.php",
minLength: 1,
change: function(event, ui)
{
$.post("../phpfiles/search.php", data{post_data: component_name});
}
});
});
</script>
修改后的search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query="";
if($_POST['post_data']=="customer")
{
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc())
{
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
}
?>
谁能帮助我实现这一目标?
我将以下链接用于jquery-ui和jquery api部分:
这可能是一个有点复杂的广告,希望对您有所帮助。 您的示例未向数据库提供任何示例数据或架构,因此我不得不做出很多猜测。 您需要进行调整。
考虑一下您是否具有不同的输入字段,您可以:
HTML
<div class="ui-widget">
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input class="entry-field" name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
<tr>
<td>
<label>Contact: </label>
<input class="entry-field" name="contact" id="contact" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_ccontact_request">
</td>
</tr>
</table>
</form>
</div>
JavaScript的
$(function() {
$(".entry-field").autocomplete({
source: function(req, resp) {
// determine which field we're working with
var type = $("this").attr("id");
// collect the entry in the field
var term = req.term;
// Prepare our response array
var responses = [];
// PErform POST Request to our Search and accept JSON results
$.ajax({
url: "../phpfiles/search.php",
data: {
t: type,
q: term
},
type: "POST",
dataType: "JSON",
success: function(results) {
$.each(results, function(key, val) {
responses.push(val);
});
}); resp(responses);
},
minLength: 1
}
});
$("#customer_report_request").submit(function(e) {
e.preventDefault();
if ($("#customer").val().length) {
// perform POST to a PHP search for that specific customer details
} else {
// performn a post to a PHP search for that specific contact details
}
// populate result DIV on page with resulting data from POST
});
});
PHP:search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
// get search query
$searchTerm = $_POST['q'];
// get search type
$searchType = $_POST['t'];
//get matched data from customer table
if($searchType == "customer"){
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Company_Name LIKE '?%'");
} else {
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Contact_Name LIKE '?%'");
}
/* bind parameters for markers */
$stmt->bind_param("s", $searchTerm);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
if($searchType == "company"){
$data[] = $row['Company_Name'];
} else {
$data[] = $row['Contact_Name']
}
}
//return json data
header('Content-Type: application/json');
echo json_encode($data);
?>
因此,发生了很多事情。 从您的PHP开始。 它很容易受到SQL注入的攻击,因此我利用MySQLi Prepare来保护事物。 我们希望将数据发布到此脚本,并且希望满足以下条件: query
和type
。 如果没有类型,则可以设置默认值。 可能想添加一个查询query
,但它应始终具有1个字符。
我们使用source
选项的function方法将此数据获取到我们的搜索脚本中。 查看更多: http : //api.jqueryui.com/autocomplete/#option-source
功能:第三个变体是回调,提供了最大的灵活性,可用于将任何数据源连接到自动完成。 回调有两个参数:
- 具有单个
term
属性的request
对象,它引用文本输入中当前的值。 例如,如果用户在城市字段中输入“ new yo”,则“自动完成”term
将等于“ new yo”。response
回调,它需要一个参数:向用户建议的数据。 该数据应根据提供的term
进行过滤,并且可以采用上述针对简单本地数据描述的任何格式。 提供自定义源回调以处理request
期间的错误时,这一点很重要。 即使遇到错误,也必须始终调用response
回调。 这样可以确保小部件始终具有正确的状态。
因此,我们可以添加到$.ajax()
调用中并利用error
回调。 基本上,我们最终将空数组发送回response
。
因此,我们向PHP发送一个发送搜索项,我们获取JSON数组数据,并将其通过管道传递到我们自己的数组中以发送回response
,用户将获得一个结果列表。
还是有点笨拙,如果您习惯了用户的习惯,那也没关系。 您可以精简它,也可以对结果进行分类。 这样,您可以拥有一个搜索字段。 同样,一旦选择了某些内容或更改了字段,您就可以再次使用AJAX从另一个PHP提取这些细节,而另一个PHP从数据库中获取所有数据。 这将导致不必等待页面再次加载等。
我希望这个答案能回答您的问题,并且我怀疑它还会提出更多问题。 继续搜索,有很多答案。 有时,将一个大问题分解为较小的单个问题比解决整个问题更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.