[英]How to insert contents from AJAX result into an element without removing its existing contents?
[英]How to load contents to an existing div with jquery load() without removing the divs existing contents
我想將php文件的內容加載到已經存在的div中。 我嘗試了以下代碼,但是在Firebug中未定義錯誤負載。 有人能幫我嗎?
$("#post_button").click(function(){
var result = load("<?php echo SITEURL; ?>/newpost.php", data);
$("#parent-post").append(result, function() {
special_functions();
});
$.load()
是$.ajax()
的便捷方法,默認情況下會替換選擇器的html。 為了提高靈活性,可以使用$.get
類的另一種方法,該方法使您可以訪問返回數據並且不操縱DOM。 然后,您可以追加而不是替換
http://api.jquery.com/jQuery.get/
$("#post_button").click(function(){
$.get("<?php echo SITEURL; ?>/newpost.php", data, function( returnData){/* assuming your data var is data to send to server*/
$("#parent-post").append(returnData);
special_functions();
});
});
最簡單的方法可能是將遠程內容加載到div的子元素中,而不是div本身中。 注意我在jquery中所做的更改(必須在要將內容加載到其中的元素上調用load)。
<div id="parent-post">
Lorem ipsum dolor sit amet.
<div id="inner_div"></div>
</div>
<script type="text/javascript">
$("#post_button").click(function(){
$("#inner_div").load("<?php echo SITEURL; ?>/newpost.php",
data, special_functions);
});
</script>
此處在哪里定義load
方法? 如果您期望它是jQuery load
那么您應該以這種方式使用它。
$(element).load('url');
由於您希望添加內容而不是替換內容,因此使用load
是正確的方法。 使用任何其他方法,如get
, post
或ajax
,從php獲取內容,然后將其附加到所需的容器中。
$.get("<?php echo SITEURL; ?>/newpost.php", function(response){
$("#parent-post").append(response);
special_functions();
});
$.getJSON("<?php echo SITEURL; ?>/newpost.php", function(data){
$("#parent-post").append(data);
special_functions();
});
其中getJSON可以是$ .get,$。post。
干得好。 由於AJAX從服務器中提取數據,因此它使用了異步行為,這意味着您需要給它一個回調函數來告訴它在獲取數據時該怎么做:
$("#post_button").click(function(){
$.post("<?php echo SITEURL; ?>/newpost.php", data, function(result) {
$("#parent-post").append(result);
special_functions();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.