我有一个网站,每个用户的页面都显示评论并允许其他用户添加评论。我希望拥有它,以便添加评论表单位于页面上,当用户添加评论时,它会被添加到数据库中并使用 AJAX 显示在评论部分中。我使用 jQuery 进行 AJAX 并使用 LINQ to SQL 来处理数据库逻辑。如何做到这一点,以便在将评论添加到数据库后,刷新和更新评论部分而不刷新页面?
最佳答案
您需要利用 jQuery ajax 调用触发的“成功”(或“完成”)事件来触发后续的 AJAX 调用来刷新您的评论内容。这可能看起来像(有翅膀,未经测试):
function UpdateComments(){
resultHTML = jQuery.ajax({
type: 'GET',
url: 'Comments/List/UserID'
}).responseText;
$('#comments').html(resultHTML);
}
function PostComment(targetUserID, commenterUserID, comment)
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: $.toJSON({review: comment, id:targetUserID, commenter:commenterUserID}),
dataType: 'json',
url: 'Comments/Add',
success: function(result){
// Only update comments if the post was successful:
resultJson = $.evalJSON(result);
if(resultJson['success'] == true){
UpdateComments();
}
}
});
编辑 JSON 代码将使用 jquery 插件 jquery-json ( http://code.google.com/p/jquery-json/ )
关于javascript - ASP.NET MVC AJAX 与 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/578443/