views:

39

answers:

4

Hi

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:

 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?

Thanks

+1  A: 

Use the replace() method:

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

data: '{ id: "' + esc_quot(news_id) + '", title: "' + esc_quot(news_title) + '", body: "' + esc_quot(news_body) + '" }',
Frédéric Hamidi
A: 

hi!

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

phpjs.org

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

Naresh
A: 

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

+1  A: 

Rather than using one-off code, go with a Javascript JSON encoder (such as provided by MooTools' JSON utility or 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 natively via 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 library is one that does this.

data: JSON.stringify({
  id: news_id,
  title: news_title,
  body: news_body
}),
outis
Thank you. Now it's working properply but i've a question. I'm just using "JSON.stringify" (my browser is FF 3.6.11), so it works without the implentation of YUI JSON library. But how should i handle it for older browsers? I guess that for older browsers, it should be used YUI like this "YAHOO.lang.JSON.stringify", but do i need to change anything or just using data: JSON.stringify the browser checks for JSON.stringify and if it's a old browser, it will use the YAHOO.lang.JSON.stringify instead? Thanks
Guilherme Cardoso
The sample wasn't specifically targeting YUI. If you choose to rely on YUI, you'd use its API and let it do whatever under the hood. For a lighter library, take a closer look at the open source [JSON.js](http://www.JSON.org/json2.js). It's transparent, implementing the global JSON object only if a native version doesn't exist. As more browsers support the native JSON object (it's part of the [ECMAScript 3.1](http://wiki.ecmascript.org/doku.php?id=es3.1:json_support) standard), you can eventually phase out JSON.js simply by not including it, whereas YUI would require rewriting the code.
outis