转义jquery ajax发送的字符串中的所有特殊字符 [英] Escape all special characters in a string that is sent by jquery ajax
问题描述
我正在尝试在将contentType: "application/json; charset=utf-8",
ajax发布到Web服务时以键值对的形式发送文本.我面临的问题是,如果其中一个参数(接受用户的文本)带有引号(),则会破坏代码[Eror message:Invalid object in in].到目前为止,我已经尝试了这些,但均未成功>
I am trying to send text in key value pairs while doing a contentType: "application/json; charset=utf-8",
ajax post to a web service. The problem I am facing is that if one of the parameters (that accepts text from the user) has quotes (") it breaks the code [Eror message: Invalid object passed in ] . So far I have tried these without any success
var text = $("#txtBody").val();
var output1 = JSON.stringify(text);
var output2 = text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
关于如何转义jquery ajax帖子的特殊字符的任何想法?
Any ideas on how to escape the special characters for the jquery ajax post?
推荐答案
为什么不使用escape
?
escape(text);
https://developer.mozilla.org/en/DOM/window.escape
编辑!!!!
如评论中所述,已弃用.
As mentioned in comments, this is deprecated.
不建议使用的escape()方法计算一个新字符串,其中某些字符已由十六进制转义序列替换.请改为使用encodeURI或encodeURIComponent.
The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use encodeURI or encodeURIComponent instead.
请使用以下选项之一:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
这篇关于转义jquery ajax发送的字符串中的所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!