babycakes
babycakes

Reputation: 546

JSON html string is not being converted to html by innerhtml

I am using javascript and php and need to pass some HTML in the JSON variable (PHP->JS).

Unfortunately, due to some environmental constraints I am limited in the jQuery I can use. Using things such as jQuery.parseJSON(str) and $.parseJSON(str) throw unexpected token errors.

Therefor I need a purely javascript approach to handling html in a JSON variable. Currently, the HTML string is just printed as a string on the page, though I need it to take effect as HTML.

My JS code is as follows:

document.getElementById("activeDescription").innerHTML = response['description'];

and the results ends up just being text on the HTML page as follows:

<p>helloworld</p>

whereas I expect just

helloword

to be displayed on the HTML page. On alert(response['description']) I receive

&lt;p&gt;&lt;span class=&quot;

EDIT

When I use

jQuery.parseJSON('{"name":"John"}');

everything is peachy but this code

jQuery.parseJSON(response['description']);

gives me an "Uncaught SyntaxError: Unexpected token & " error

Upvotes: 0

Views: 866

Answers (1)

Luis Ramos
Luis Ramos

Reputation: 121

Most probably a encoding problem. You can fix by decoding the characters.

In javascript:

var div = document.createElement('div');
div.innerHTML = encoded;
var decoded = div.firstChild.nodeValue;

In PHP, look at this link: http://www.php.net/manual/en/function.htmlentities.php

Upvotes: 1

Related Questions