Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 831
Gui Avatar asked Oct 27 '10 08:10

Gui


2 Answers

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
}),
like image 82
outis Avatar answered Oct 14 '22 18:10

outis


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) + '" }',
like image 41
Frédéric Hamidi Avatar answered Oct 14 '22 18:10

Frédéric Hamidi