2010-07-26 58 views
3

我有一个表单,如果用户输入搜索查询,它的参数应该通过jquery传递,获得结果后它应该将结果加载到div容器中。因为我对jquery不太熟悉,我会如何做到这一点?通过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类:

$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); 
} 

回答

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(); 
}); 
+0

谢谢,这有效,但如果我想在#bquote容器中显示结果呢?另外,由于它正在获取数据,因此没有迹象表明它在后台获取数据。我会在哪里显示loadeR? – input 2010-07-27 00:41:36

+0

你现在已经在回答所有问题了:)检查编辑好的零件... – KakambaWeb 2010-07-27 00:51:11

+0

谢谢!公认。 :) – input 2010-07-27 01:07:31

0

使用$ _ POST相反的,你可以使用$ _GET或$ _REQUEST如下所示:

var searchString = $(".bsearch").val(); 
$("#bquote").load("path_to_php_file.php?search="+searchString); 

然后,在PHP中,与

$_GET 
1

更换

$_POST 

...如果你想往下走阿贾克斯路线...

$(".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()

+0

thanks!如果我想在#bquote容器中显示结果怎么办? – input 2010-07-27 00:40:30