![](/img/trans.png)
[英]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.