我必须形成一个JSON字符串,其中一个值有新的行字符。这必须转义,然后使用AJAX调用发布。谁能建议一种用JavaScript转义字符串的方法?我没有使用jQuery。
当前回答
最好使用JSON.parse(yourUnescapedJson);
其他回答
我使用内置的jQuery.serialize()从文本区域提取值以urlencode输入。专业的部分是,你不需要搜索替换每一个特殊的字符在你自己和我也保持换行符和转义html。为了序列化工作,似乎输入字段需要有一个name属性,但它也添加了相同的属性转义字符串,需要被替换掉。也许不是你想要的,但对我有用。
var myinputfield = jQuery("#myinputfield");
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');
如果您的服务器端脚本是PHP,请使用json_encode(), Json_encode()转义换行符和其他意想不到的标记 (如果不使用PHP,请为您的脚本语言寻找类似的函数)
然后在JavaScript中使用$.parseJSON(),完成!
EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.
原文:如果你的谷歌一直登陆你这里,你的api抛出错误,除非你的JSON双引号转义("{\"foo\": true}"),所有你需要做的是stringify两次,例如JSON.stringify(JSON.stringify(bar)))
使用encodeURIComponent()对字符串进行编码。
例如。var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));
你不需要解码它,因为web服务器会自动做同样的事情。
获取JSON和.stringify()。然后使用.replace()方法将所有出现的\n替换为\\n。
编辑:
据我所知,没有知名的JS库用于转义字符串中的所有特殊字符。但是,你可以链接.replace()方法,像这样替换所有的特殊字符:
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server.
但这很恶心,不是吗?函数的美妙之处在于,它们允许您将代码分解成片段,并保持脚本的主要流程干净,并且没有8个链式的.replace()调用。因此,让我们将该功能放入一个名为escapeSpecialChars()的函数中。让我们继续把它附加到String对象的原型链上,这样我们就可以直接在String对象上调用escapeSpecialChars()。
像这样:
String.prototype.escapeSpecialChars = function() {
return this.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
};
一旦我们定义了这个函数,我们代码的主体就像这样简单:
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server
推荐文章
- 如何在javadoc中转义@字符?
- 清除JavaScript中的缓存
- 如何在使用Javascript替换DOM元素?
- 在Redux应用程序中哪里写localStorage ?
- 如何在ReactJS中从“外部”访问组件方法?
- 为时刻添加持续时间(moment.js)
- 如何在JavaScript中获得时区名称?
- 在JSON键名中哪些字符是有效的/无效的?
- jQuery中的live()转换为on()
- 如何区分鼠标的“点击”和“拖动”
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 如何转义JSON字符串包含换行字符使用JavaScript?
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱