我在使用一些基本的 ajax 和 asp.net 网络服务时遇到了问题。在我的网站页面中,我有一个到达文本编辑器的文本框,当我输入文本并尝试提交它时,ajax 应该获取文本并将其传递给 asp.net web 服务。当句子不包含转义字符时,一切顺利,但是当它包含转义字符时,asp.net web 服务会给我错误 500。在调试时它甚至不会进入 web 服务。
所以问题是:我该如何修复它?
这是我的代码。 Javascript:
//posting the user comment
function postComment() {
var comment_body = $("textarea[id*='txt_editor']").val();
$.ajax({
type: "POST",
url: "Article.asmx/postComment",
data: "{'article_id': '" + article_id + "', 'comment_body' : '" + comment_body + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
page_num = 1;
getComments();
clearComment()
}
});
}
Web 服务看起来像这样:
//posting the comment to database
[WebMethod]
public int postComment(int article_id, string comment_body)
{
try
{
using (ForMarieDataContext forMarie = new ForMarieDataContext())
{
tbl_article_comment newComment = new tbl_article_comment();
newComment.article_id = article_id;
newComment.comment_author = "Dmitri";
newComment.comment_date = DateTime.Now.ToString();
newComment.comment_body = comment_body;
forMarie.tbl_article_comments.InsertOnSubmit(newComment);
forMarie.SubmitChanges();
}
return 1;
}
catch(Exception ex)
{
return 0;
}
}
}
这是基本代码,我将向其中添加更多代码以检查安全性。 但是现在,我需要以某种方式对文本中的转义字符进行处理。 提前致谢。
最佳答案
让jQuery处理参数的转义和编码:
$.ajax({
type: "POST",
url: "Article.asmx/postComment",
data: { article_id: article_id, comment_body: comment_body },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
page_num = 1;
getComments();
clearComment()
}
});
注意 data
属性。
关于asp.net - 转义字符和错误 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1779420/