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");
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With