Javascript 在ajax数据库插入后更新div
因此,我从数据库中提取了一些评论,并在div中进行了回应 我通过一个表单输入新的注释,并使用ajax将它们插入数据库 我希望div中的评论在发布后立即更新并显示新的评论 如何刷新div以显示新内容,而无需再次加载页面 javascript是这样的:Javascript 在ajax数据库插入后更新div,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,因此,我从数据库中提取了一些评论,并在div中进行了回应 我通过一个表单输入新的注释,并使用ajax将它们插入数据库 我希望div中的评论在发布后立即更新并显示新的评论 如何刷新div以显示新内容,而无需再次加载页面 javascript是这样的: // ... goes after Validation if (check == true) { $.ajax({ type: "POST", url: "process/addcomment.php", data: $targ
// ... 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;
});
})
谢谢您的帮助。我想您应该使用 在顶部发表新评论 或者 在底部发表新的评论 使用后立即
$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>");
也值得查看您的响应。databaseSuccess,您可能希望更严格地比较它,就像使用==,因为布尔值并不总是像您期望的那样工作,因为我不确定您的响应文档的格式是否正确,它是否正确地解释为布尔值。您应该从响应json中提取所需的数据,并生成一个Html,用于将注释id附加到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>');
}
});
}
反应如何?如果你做了console.logresponse,你会得到什么?我猜你在网络上看到了一些很酷的东西,比如堆栈溢出,你要找的是WebSocket或长轮询,你没有意识到这比你想象的复杂得多。你可能会发现这很有帮助,尤其是在最下面简单的AJAX示例中。请注意,除非您另有指定,否则jqueryajax交换数据的默认方法(即数据类型)是HTML。