JavaScript - 如何在 var 中转义引号以通过 Json 传递数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4031324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - How escape quotes in a var to pass data through Json
提问by Gui
I'm passing some data through Json to a Webservice. My problem is that i'm passing html (from a tinyMCE input), so the var has content using quotes and that's giving me problems. I'm passing the values like this:
我正在通过 Json 将一些数据传递给 Web 服务。我的问题是我正在传递 html(来自 tinyMCE 输入),所以 var 的内容使用引号,这给我带来了问题。我正在传递这样的值:
data: '{ id: "' + news_id + '", title: "' + news_title + '", body: "' + news_body + '" }',
Is there anyway to espace quotes in javascript, so i can send html in that news_body var?
反正有没有在javascript中espace引号,所以我可以在那个news_body var中发送html?
Thanks
谢谢
回答by Frédéric Hamidi
回答by outis
Rather than using one-off code, go with a Javascript JSON encoder (such as provided by MooTools' JSON utilityor JSON.js), which will take care of encoding for you. The big browsers (IE8, FF 3.5+, Opera 10.5+, Safari & Chrome) support JSON encoding and decoding nativelyvia a JSON object. A well-written JSON library will rely on native JSON capabilities when present, and provide an implementation when not. The YUI JSON libraryis one that does this.
与其使用一次性代码,不如使用 Javascript JSON 编码器(例如由MooTools 的 JSON 实用程序或JSON.js 提供),它将为您处理编码。大浏览器(IE8,FF 3.5+歌剧10.5+,Safari浏览器和铬)支持JSON编码和解码本机经由JSON对象。编写良好的 JSON 库在存在时将依赖于本机 JSON 功能,并在不存在时提供实现。该YUI JSON库是一个做到这一点。
data: JSON.stringify({
id: news_id,
title: news_title,
body: news_body
}),
回答by user396404
Use the function below:
使用下面的函数:
function addslashes (str) {
return (str+'').replace(/[\"']/g, '\$&').replace(/\u0000/g, '\0');
}
For example:
例如:
data: '{ id: "' + addslashes(news_id) + '", title: "' + addslashes(news_title) + '", body: "' + addslashes(news_body) + '" }',
A lot of functions like this can be found at http://phpjs.org/functions/index
很多这样的函数可以在http://phpjs.org/functions/index找到