ASP.NET MVC AJAX与jQuery [英] ASP.NET MVC AJAX with jQuery

查看:122
本文介绍了ASP.NET MVC AJAX与jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,每个用户的页面显示评论,并允许其他用户添加评论。我想拥有它,所以添加评论表单是在页面上,当用户添加评论时,它被添加到数据库并显示在AJAX的注释部分。我使用jQuery的AJAX和LINQ to SQL来处理数据库逻辑。如何做到这一点,以便在将注释添加到数据库后,注释部分将被刷新和更新,而不刷新页面?

I have a site where each user's page shows comments and allows other user's to add comments. I want to have it so the add comments form is on the page and when a user adds a comment, it is added to the database and shows up in the comment section with AJAX. I am using jQuery for the AJAX and LINQ to SQL to handle the database logic. How would go about doing this so that after the comment is added to the database, the comments section is refreshed and updated without refreshing the page?

推荐答案

您需要利用jQuery ajax调用触发的成功(或完成)事件来触发后续AJAX调用,以刷新您的评论内容。这可能看起来像是(未经测试):

You would need to take advantage of the 'success' (or 'complete') event that is fired by the jQuery ajax call to fire a subsequent AJAX call for refreshing the content of your reviews. This would probably look something like (winged it, untested):

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/

EDIT The JSON code would make use of the jquery plugin jquery-json (http://code.google.com/p/jquery-json/)

这篇关于ASP.NET MVC AJAX与jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆