转义由jquery ajax发送的字符串中的所有特殊字符

dev*_*747 18 jquery text

我正在尝试在向contentType: "application/json; charset=utf-8",Web服务执行ajax发布时发送键值对中的文本 .我面临的问题是,如果其中一个参数(接受来自用户的文本)有引号(")它会破坏代码[Eror消息:传入的无效对象].到目前为止,我已经尝试过这些但没有成功

var text = $("#txtBody").val(); 
var output1 = JSON.stringify(text); 
var output2 = text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
Run Code Online (Sandbox Code Playgroud)

关于如何逃避jquery ajax帖子的特殊字符的任何想法?

Tre*_*vor 33

为什么不用escape

escape(text);
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en/DOM/window.escape

编辑!!!!

正如评论中所提到的,这已被弃用.

不推荐使用的escape()方法计算一个新字符串,其中某些字符已被十六进制转义序列替换.请改用encodeURI或encodeURIComponent.

而是使用以下之一:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent


zay*_*tro 13

对于那些会发现这个问题的人: 不要使用它已经从Web中删除的方法 使用encodeURIComponent()encodeURI()代替
encodeURIComponent()
encodeURI()

  • 不,永远不要使用encodeURI(),它不可靠并且基于猜测。encodeURI 根据“&”和“=”字符猜测数据名称和值的开始和结束位置,并且该猜测可能是错误的。作为一个直接的例子,这个url被encodeURI错误地编码:`encodeURI("http://example.org/?foo=i love my mother&father");` - 这里foo应该是`i love my mother&father`,但是encodeURI将其编码为`我爱我的母亲` - 同时,encodeURIComponent进行了0次猜测,并且在这里正常工作:`"http://example.org/?foo="+encodeURIComponent("i love my mother&father");` (2认同)