こんにちは、私は jQuery を使用するのが初めてで、Web サイトの検索機能に AJAX 関数を使用したいと考えています。ただし、関数に関連しない PHP を使用した例しか見つからないため、これを学ぶのに少し苦労しています。私は現在、この youtube の例jQuery Youtube Exampleから学ぼうとしています。ただし、これを実装するのは難しいようです。
私が達成しようとしていることについて少し。郵便番号を検索バーに入力し、AJAX を使用して一致するすべての関連データ フィールドを取得して、検索バーのすぐ下の div に表示されるようにしたいと考えています。
私は jQuery にあまり詳しくないので、これが正しい方法であるかどうかわかりませんが、どんな意見も歓迎します。前もって感謝します!
私のコードはそうです
index.php
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<?php include("header.php");
$houseobject = new House();
$houseobject->search($_POST['term']);?>
<div id="mainContent">
<div id="searchformWrap">
<br/><h2>Search for Accomodation</h2>
<div id="searchform"><br/><br/><br/>
<form method="post" action="index.php" name="search" id="search_form">
<div class="searchrow">
<div class="searchlabel">Location</div>
<div class="searchinput">
<input type="text" name="term" id="term" />
<input type="submit" name="submit" id="searchsubmit" value="Search"/>
</form>
<div class="help">e.g. 'PO5' or 'Portsmouth'</div>
</div> <!-- end input -->
</div> <!-- end .row -->
<div id="searchquery"> </div>
</div> <!-- End maincontent -->
classes/class.House.inc
<?php
include ("connect.class.Database.inc");
class House extends Database {
public function search ($term){
$query = "SELECT * FROM houses
WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()) {
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
} else{
echo 'No Records Found';
}
echo json_encode($data);
}
}
js/ajax.js
$('input#searchsubmit').on('click', function() {
if ($.trim(term) != '') {
$.post('classes/class.House.inc', {term: term}, function(data) {
$('div#searchquery').text(data);
});
}
});
}
私は通常、index.php のフォームを指定して結果を取得しています...
検索.php
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">id</th>
<td width="95">bedrooms</td>
<td width="140">description</td>
<td width="104">roadname</td>
<td width="71">postcode</td>
</tr>
<?php
require("classes/class.House.inc");
$obj = new House();
if ($data = $obj->search($_POST['term']))
{
foreach($obj->data as $val){
extract($val);
}
}
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $bedrooms; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $roadname; ?></td>
<td><?php echo $postcode; ?></td>
</tr>
</table>