2010-07-26 67 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