注意:我希望这个Show data from database on load完全正确
我正在使用ajax进行实时搜索一切正常,但是仅需要解决一个问题,因此问题是ajax无法在页面加载中工作,我的意思是我正在从这样的URL获取数据。即http://localhost/basic_hackings/search.php?q=usman
,这里的“üsman”是要搜索的数据。因此,一切工作正常,但刷新后消失了,我也在jQuery中使用onload
,但徒劳无功。详细了解代码。
ajax_search.php
是:
<?php
$host = "localhost";
$dbUser = "root";
$password = "";
$database = "basic_hackings";
$dbConn = new mysqli($host,$dbUser,$password,$database);
if($dbConn->connect_error)
{
die("Database Connection Error, Error No.: ".$dbConn->connect_errno." | ".$dbConn->connect_error);
}
$search_data = $_GET['q'];
$qry = "select first_name, last_name, email, phone, city, country from customers where first_namelike '%$search_data%'";
$rs = $dbConn->query($qry);
$fetchAllData = $rs->fetch_all(MYSQLI_ASSOC);
$createTable = '<table>';
$createTable .= '<tr>';
$createTable .= '<th>First Name</th>';
$createTable .= '<th>Last Name</th>';
$createTable .= '<th>Email</th>';
$createTable .= '<th>Phone</th>';
$createTable .= '<th>City</th>';
$createTable .= '<th>Country</th>';
$createTable .= '</tr>';
foreach($fetchAllData as $customerData)
{
$createTable .= '<tr>';
$createTable .= '<td>'.$customerData['first_name'].'</td>';
$createTable .= '<td>'.$customerData['last_name'].'</td>';
$createTable .= '<td>'.$customerData['email'].'</td>';
$createTable .= '<td>'.$customerData['phone'].'</td>';
$createTable .= '<td>'.$customerData['city'].'</td>';
$createTable .= '<td>'.$customerData['country'].'</td>';
$createTable .= '</tr>';
}
$createTable .= '</table>';
echo $createTable;
$rs->close();
$dbConn->close();
?>
和ajax_search.js
是:
$(document).ready(function() {
$('#form1').submit(function(e) {
e.preventDefault();
var search_data = $('#search_data').val();
$.ajax({
url: "ajax_search.php/?q=" + search_data,
type: "GET",
data: new FormData($("#form1")[0]),
contentType: false,
processData: false,
beforeSend: function(data) {
$(".main_search_content").html("");
$(".main_search_content").addClass("searching");
},
success: function(data) {
setTimeout(function() {
if (!(data == "")) {
$(".main_search_content").html(data);
}
else {
$(".main_search_content").html("Nothing Found!");
}
$(".main_search_content").removeClass("searching");
}, 500)
}
});
history.pushState(null, null, "?q=" + search_data);
}
});
});
这里是site.js
,我正在使用onload
,请参见:
$(window).on("load", function() {
$.ajax({
url: 'ajax_search.php',
success: function(data){
$(".main_search_content").html(data);
}
});
});