问题描述
这个问题已经被问过,但我必须意识到,我没有带发现了真正的/最好的方法,这样做的!
This question has been asked before, but I must realize, I havn't found the real/best way of doing this!
问题是,我想EN code我从AJAX调用才能得到响应prevent跨站点脚本(XSS)攻击。我有一个表格有一个文本框和提交按钮。当提交,该值被发送到服务器,并返回到客户端。在这里,我需要HTML EN code的响应,因为消息如可能是警戒('你好')等。
The issue is, that I want to encode the response I get from the AJAX call in order to prevent Cross-site scripting (XSS) attacks. I have a form with a textbox and submit-button. When submitting, the value is posted to the server and returned to the client. Here i need to html encode the response, as the message e.g. could be " alert('Hello') " etc.
我如何连接code item.Message 以下?
How do I encode item.Message in the following?
查看
$(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>
控制器动作
[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);
}
希望能得到一个答案,这是推动我疯了!类似的问题给予此处,但我不能看到如何使用的.text在我的情况。
Hope to get an answer, this is driving me insane!A similar question was given here, but I cant see how to use .text in my case.
更新:这是真正的解决方案?
推荐答案
尝试这样的:
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
}
这篇关于MVC和jQuery,AJAX,HTML-CN code JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!