jquery - MVC、JQUERY、AJAX、HTML 编码 JSON 响应

标签 jquery asp.net-mvc ajax json html-encode

这个问题之前已经被问过,但我必须意识到,我还没有找到真正/最好的方法!

问题是,我想对从 AJAX 调用获得的响应进行编码,以防止跨站点脚本 (XSS) 攻击。我有一个带有文本框和提交按钮的表单。提交时,该值被发布到服务器并返回给客户端。这里我需要对响应进行 html 编码,例如消息可能是“alert('Hello')”等。

如何在以下内容中对 item.Message 进行编码?

查看

$(document).ready(function () {

    $("form[action$='SubmitChatMessage']").submit(function () {
        $.ajax({
            url: $(this).attr("action"),
            type: "post",
            dataType: "json",
            data: $(this).serialize(),
            success: function (response) {
                $("#chatMessages").empty();

                var chatMessages = "";
                $.each(response, function (i, item) {
                    chatMessages += '<div>' + item.Message + '</div>';
                });

                $("#chatMessages").html(chatMessages);
                $("#message").val(''); // Clear the textbox value
            }
        });
        return false;
    });
});

<div id="chatContent">
    <% using(Html.BeginForm("SubmitChatMessage", "ProductDetails"))
       {%>
    <%: Html.TextBox("message")%>
    <%: Html.Hidden("productId", Model)%>
    <input type="submit" value="Tilføj" />
    <% }%>
    <div id="chatMessages">
    </div>
</div>

Controller 操作

[HttpPost]
[ValidateInput(false)]
public JsonResult SubmitChatMessage(string message, Guid productID)
{

    // 1. Store message in db

    // 2. Fetch messages from db
    List<Message> chats = DB.GetMessages(productID);
    var json = (from c in chats 
               select new {Message = c.Message, CreatedDate = c.Created});

    return Json(json);
}

希望得到答案,这让我发疯! 给出了类似的问题here ,但我不知道如何在我的情况下使用 .text 。

更新: Is this really the solution?

最佳答案

尝试这样:

success: function (response) {
    var messages = $('#chatMessages');
    messages.empty();

    $.each(response, function (i, item) {
        messages.append(
            $('<div/>', {
                text: item.Message
            })
        );
    });

    $('#message').val(''); // Clear the textbox value
}

关于jquery - MVC、JQUERY、AJAX、HTML 编码 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6793588/

相关文章:

php - 除非打开开发人员工具,否则 jQuery $.post() 函数在 IE 中不起作用

javascript - 在Vue和Ajax中获取请求的http状态码

javascript - $.post 和 AJAX 在服务器上不工作,但在本地主机上工作正常

jquery - Ajax 不工作并且控制台没有给出任何错误-MVC

jquery - 遍历 HTML : how can I hide a color when I move to another element?

javascript - 如何检测使用 JQuery(或 Javascript)选择的隐式 HTML 选项

asp.net-mvc - ASP.NET MVC 返回空 View

jquery 将字符串与 .val() 进行比较;非预期结果

c# - 将 asp.net core 从 .net 5 移植到 .net 6 时首页加载缓慢

c# - ASP.Net MVC Razor Sum 和 Count 函数