我有一个表单,如果用户输入搜索查询,其参数应该通过jquery传递,在获得结果后,它应该将结果加载到div容器中。因为我对jquery不是很精通,我该怎么做?
HTML:
//currently the data is being displayed on pageload:
$(document).ready(function() {
$("#bquote").load("quotes_in.php")
});
$(".bsearch")
.keydown(function() {
//pass the parameter to the php page
//display in div #bquote
});
<!-- Begin Search -->
<div id="search" style="display:none;">
<input type="text" class="bsearch" name="search" value="Search" />
</div>
<!-- End Search -->
php [使用OOP]:
if (isset($_POST["search"]))
{
$quotes->searchQuotes();
}
php class:
$search = $_POST['search'];
$sql = "SELECT * FROM thquotes WHERE cQuotes LIKE '%"
. mysql_real_escape_string($search) ."%' ORDER BY idQuotes DESC";
try {
$query = $this->_db->prepare($sql);
$query->execute();
if(!$query->rowCount()==0)
{
while($row = $query->fetch())
{
echo $this->formatSearch($row);
}
答案 0 :(得分:3)
我会这样做:
$(".bsearch").keydown(function() {
//create post data
var postData = {
"bsearch" : $(this).val(),
"anotherParam" : "anotherValue"
};
//make the call
$.ajax({
type: "POST",
url: "yourAjaxUrl.php",
data: postData, //send it along with your call
success: function(response){
alert(response); //see what comes out
//fill your div with the response
$("#bquote").html(response);
}
});
});
修改强>
如需放置装载机,您需要在此处查看:
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
并显示加载程序图像,例如:
$("#loading").ajaxStart(function(){
$(this).show();
});
并在ajax调用完成后隐藏它:
$("#loading").ajaxComplete(function(){
$(this).hide();
});
答案 1 :(得分:1)
如果你想沿着ajax路线走......
$(".bsearch").keydown(function() {
// Get the current input value
var value = $(this).val();
//pass the parameter to the php page
$.ajax({
type: "POST",
url: "some.php", // replace this with the right URL
data: "bsearch=" + value,
success: function(msg){
$("#search").html(msg);
}
});
});
阅读jQuery.ajax(),如果您将该搜索框转换为正确的格式,请使用jQuery.serialize()
答案 2 :(得分:0)
您可以使用$ _GET或$ _REQUEST,而不是使用$ _POST,如下所示:
var searchString = $(".bsearch").val();
$("#bquote").load("path_to_php_file.php?search="+searchString);
然后,在PHP中,替换
$_POST
...与
$_GET