tags:

views:

3929

answers:

3

In my Ajax request (using jQuery) I am returning a JSON response.

So json.Html will have a string of HTML I want to append inside a div.

On the server side, do I have to escape the HTML at all?

In my MVC action, I am returning:

return Content("{html: ???????}, "application/json");
+2  A: 

You only need to add slashes to quotes and slashes (ala \" and \\) when escaping content to be put into a JSON string. HTML characters mean nothing inside a JSON string, so they're fine :)

Of course, make sure your string is itself well-formed (X)HTML so that it doesn't explode when inserted into the div.

singpolyma
what about \a \b \c, there are all ok?
Blankman
+6  A: 

An alternative solution would be to simply return the HTML and use jQuery's load():

$('#someDiv').load('servershtml.html');

To do it your way though, you would need only to escape double quotes and backslashes.

The specification is very readable and short.

cobbal
+1  A: 

If you set the dataType configuration option to 'json' then the object passed to the complete event will be that javascript object. Basically, jQuery will do the work of converting the response content (assuming its properly formatted JSON) to a javascript object. Example...

$.ajax({
    dataType: 'json',
    complete: function(myJsonObject) {
        alert(myJsonObject.someMember);
    }
}); //$.ajax({

If you're wondering how to generate properly formatted JSON from .net, then I would encourage you to explore Json.NET because it makes generating JSON very, very easy.

Ken Browning