Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, I am returning HTML in a JSON result, what do I have to escape?

Tags:

json

jquery

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");
like image 425
mrblah Avatar asked Mar 17 '09 04:03

mrblah


People also ask

How escape HTML tag JSON?

You're HTML values are OK, but the keys of the JSON object must be enclosed in quotes. string. quotation marks. Also, if you output this JSON object inside the script tags of an HTML page, you must escape the "</" sequence of HTML closing tags, as per this appendix in the HTML 4 specification.

How do you escape a line break in JSON?

JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.

How does JSON handle new line?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.


1 Answers

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.

like image 196
cobbal Avatar answered Oct 01 '22 18:10

cobbal