2011-03-10 96 views
0

我製作了jQuery & AJAX腳本,它使用PHP函數從API返回結果。這部分工作很好,但每次我搜索新書時,它都會刪除以前的搜索結果。jQuery&AJAX - 填充列表?

我想給它一個書ID,搜索,得到結果,並繼續這樣做。每次點擊「搜索」,我都想用更多的書籍填充一個列表。

此代碼不斷刪除我的上一本書,並將其替換爲我搜索的新書。

任何想法?

isbn.php:

<script src="http://code.jquery.com/jquery-1.5.js"></script> 
<form method="post" action="ajax.php" id="searchForm"> 
    <input type="text" name="isbn" placeholder="Search..." /> 
    <input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" /> 
</form> 

<div id="result"></div> 

{literal} 
<script> 
// attach a submit handler to the form 
$("#searchForm").submit(function(event) { 
// stop form from submitting normally 
event.preventDefault(); 

// get some values from elements on the page: 
var $form = $(this), 
term = $form.find('input[name="isbn"]').val(), 
//term = "isbn", 
url = $form.attr('action'); 
    $.post(url, { doSearch: "Search", isbn: term } , 
     function(data) { 
      var content = $(data); 
      $("#result").html(content); 
     } 
    ); 
}); 
</script> 

ajax.php這個API調用,並打印isbn.php內的結果。

回答

2

,如果你只是想那麼追加的內容:如果你想在新的結果要到結果的div使用$("#result").html(content);頂部則

$("#result").prepend(content); 

$("#result").append(content); 

告訴了jQuery用新內容替換#result中的所有HTML全部

+0

['.append()'](http://api.jquery.com/append)和['.prepend()'](http://api.jquery.com/prepend) – gnarf 2011-03-10 20:39:20

+0

非常棒!非常感謝! – Charlie 2011-03-10 20:41:36

1

問題在於您的ajax成功函數中您正在重寫#result塊的整個內容。如果您將.html更改爲.append,則應該將其添加到添加內容中而不是替換。

+0

這樣做!天啊。我做了很多試圖弄清楚的googleing,但我不知道我在找什麼。現在看起來很明顯!非常感謝! – Charlie 2011-03-10 20:38:02