I am using jQuery to call a php page (via ajax) that goes to my server to grab some data. The data is then encoded to json and returned to the page. I am then parsing the json with jQuery. I am having a problem displaying html items that are getting returned. In the json object the piece of data in question is a value to a “description” key. The json gets returned as below:
{ "description" : "Check the Wiki article to see what states require Two-Party Notification. (<a href="http://intranet.clickmotive.com/Wiki/Call%20Recording%20-%20Two%20Party%20Notification%20States.ashx" target="_blank">wiki link</a>)" }
Then i use a simple function that i found on here to decode the html. Then function i’m using is this (i pass the value of the above key through to this function):
function htmlDecode(value){
return $('<div/>').html(value).text();
}
This decodes the text it to be as follows:
Check the Wiki article to see what states require Two-Party Notification. (<a href="http://intranet.clickmotive.com/Wiki/Call%20Recording%20-%20Two%20Party%20Notification%20States.ashx" target="_blank">wiki link</a>)
This is how i am adding it to the page: (where the ‘description’ variable is being set from the json data)
$("#description").append(htmlDecode(description));
My problem is that it is displaying the full html as text and not as html. So, there is no link being created. What is my problem with this code? I must be missing something. Let me know if you have any questions! Thanks!
Your data is double
htmlentities()encoded. So there are two ways to solve this problem:jQuery
The thing what you’ve done is almost good:
Or simply call your
htmlDecode()method twice as @Dennis mentioned.JsonML
I think it would be a better idea to use JsonML instead of simple JSON for this.
JsonML is a JSON encoding of an XML document (or node), so actually it would fit better for your problem.
I wrote a JsonML jQuery plugin, which you can fetch form github. You’ll need a PHP JsonML encoder as well, which is easy to write, and I think there should be available implementations as well.