我正在尝试在向Web服务发送contentType: "application/json; charset=utf-8",
ajax帖子时发送键值对中的文本。我面临的问题是,如果其中一个参数(接受来自用户的文本)有引号(“)它会破坏代码[Eror消息:传入的无效对象]。到目前为止,我已经尝试过这些但没有成功
var text = $("#txtBody").val();
var output1 = JSON.stringify(text);
var output2 = text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
关于如何转义jquery ajax帖子的特殊字符的任何想法?
答案 0 :(得分:33)
为什么不使用escape
?
escape(text);
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
答案 1 :(得分:12)
对于那些会发现这个问题的人:
请勿使用已从网络中删除的转发方法
请改用encodeURIComponent()
或encodeURI()
encodeURIComponent()
encodeURI()
答案 2 :(得分:3)
我遇到了同样的问题,为了解决这个问题,我改变了我进行ajax调用的方式。
我有类似
的东西var datatosend = "Hello+World";
$.ajax({
"type": "POST",
"data": "info=" + datatosend
它发送信息= Hello World,用空格替换字符+。
所以我把它改成了正确的json字符串
$.ajax({
"type": "POST",
"data": {"info":datatosend},
现在它有效。信息=你好+世界
答案 3 :(得分:2)
已经有一个函数escape(var)可以帮助您转义值。它应该足以满足你所说的目的
var output2 = escape(text);
答案 4 :(得分:0)
escape()
。来源:MDN escape()
Documentation ... 程序员不应使用或假定存在这些功能和行为...
encodeURI()
。 (下面列出了替代项。)来源:MDN encodeURI()
Documentation ... 如果希望遵循最新的URL RFC3986 ...以下代码段可能会有所帮助:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
encodeURIComponent()
。 (下面列出的替代项。)来源:MDN encodeURIComponent() Documentation ... < / li>
为了严格遵守RFC 3986(保留!,',(,)和*),即使这些字符没有正式的URI分隔用法,也可以安全地使用以下字符:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
因此,如果要对除以下运算符以外的所有数据进行编码:+@?=:#;,$&
,请使用fixedEncodeURI()
。如果要包括这些字符(用于定义GET
参数以及其他用途),请使用fixedEncodeURIComponent()
。