我有一些基本的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;
}
}
}
这是基本代码,我将添加更多内容以检查安全性。 但是现在,我需要以某种方式对文本中的转义字符做一些事情。 提前谢谢。
答案 0 :(得分:2)
让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
属性。