[英]Update div after ajax database insert
所以我有一些評論從數據庫中提取出來,並呼應到div中。
我正在通過表單輸入新評論,並將它們使用ajax插入數據庫中。
我希望div中的評論更新並在新評論發布后立即顯示。
如何刷新div以顯示新內容,而無需再次加載頁面?
javascript就像這樣:
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$comment.after('<div class="success">Update Added!</div>');
else
$comment.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
謝謝你的幫助。
我想你想用
http://api.jquery.com/prepend/用於在頂部發表新評論,
要么,
http://api.jquery.com/append在底部添加了新的注釋。
使用后
$comment.after('<div class="success">Update Added!</div>');
只需添加或添加構成您的評論框的有效結構即可。 就像例如:
$("#comment-holder").append("<div class='commentbox'><p class='commenthead'>" + response.newCommentHeadline + "</p><p class='commentcontent'>" + response.newCommentContent + "</p></div>");
同樣值得研究您的response.databaseSuccess ,您可能想要更嚴格地進行比較,就像使用“ ==”一樣,因為布爾值並不總是按您期望的那樣工作,因為我不確定您的響應文檔是否采用正確的正確格式解釋為布爾值 。
您應該從響應 json提取所需的數據,並生成一個HTML以便附加到ID為“ comment”的div上,然后在應用CSS時對其進行樣式化。
我的建議是,如果您不想將服務器中的額外信息添加到評論中,則只需要將成功或失敗標記為標志,而不是將數據發送到服務器並進行檢索,則可以在成功插入到服務器中時使用本地數據數據庫
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
$("#comment").after('<div><div class="from">'+response.from+'</div><div class="message">'+response.message+'</div></div>');
}
fail:function(){
$("#comment").after('<div class="error">Something went wrong!</div>');
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.