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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:12:06  来源:igfitidea点击:

JavaScript - How escape quotes in a var to pass data through Json

javascriptjson

提问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

Use the replace()method:

使用replace()方法:

function esc_quot(text)
{
    return text.replace("\"", "\\"");
}

data: '{ id: "' + esc_quot(news_id) + '", title: "' + esc_quot(news_title) + '", body: "' + esc_quot(news_body) + '" }',

回答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找到

回答by Naresh

if you are familiar with PHP that you can use some PHP based function form

如果你熟悉 PHP,你可以使用一些基于 PHP 的函数形式

phpjs.org

phpjs.org

They made javascript function worked as PHP library functions. You can use addslashes function from here.

他们使 javascript 函数作为 PHP 库函数工作。您可以从这里使用addslashes 函数。