我必须形成一个JSON字符串,其中一个值有新的行字符。这必须转义,然后使用AJAX调用发布。谁能建议一种用JavaScript转义字符串的方法?我没有使用jQuery。
当前回答
这是一个旧帖子。但对于那些使用angular.fromJson和JSON.stringify的人来说,它仍然是有帮助的。 已弃用Escape()。 用这个代替,
var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.
ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
其他回答
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)))
RegExp单行,使用这个函数:
function escapeJSON(string) {
return string.replace(/[\n"\&\r\t\b\f]/g, '\\$&');
}
使用encodeURIComponent()对字符串进行编码。
例如。var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));
你不需要解码它,因为web服务器会自动做同样的事情。
这是一个旧帖子。但对于那些使用angular.fromJson和JSON.stringify的人来说,它仍然是有帮助的。 已弃用Escape()。 用这个代替,
var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.
ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
如果您的服务器端脚本是PHP,请使用json_encode(), Json_encode()转义换行符和其他意想不到的标记 (如果不使用PHP,请为您的脚本语言寻找类似的函数)
然后在JavaScript中使用$.parseJSON(),完成!
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?