Sending HTML Code Through JSON

Sending HTML Code Through JSON

Yes, you can use json_encode to take your HTML string and escape it as necessary to be valid JSON (it'll also do things that are unnecessary, sadly, unless you use flags to prevent it). For instance, if your original string is:

<p class="special">content</p>

...json_encode will produce this:

"<p class=\"special\">content<\/p>"

You'll notice it has an unnecessary backslash before the / near the end. You can use the JSON_UNESCAPED_SLASHES flag to prevent the unnecessary backslashes. json_encode(theString, JSON_UNESCAPED_SLASHES); produces:

"<p class=\"special\">content</p>"

Write HTML string in JSON

You should escape the characters like double quotes in the html string by adding "\"

eg: <h2 class=\"fg-white\">

How to send a JSON object using html form data

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.

$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});

Best practices for passing HTML as JSON

After a lot of researching and thinking, we've decided it's better to use Javascripts own built in functions, rather than doing something manually.

Therefore we are using JSON.stringify combined with JSON.parse, and told backend to simply html encode their markup, instead of escaping " and / manually.

Sending HTML by Json

escape your "" qoutes like \"" in the <li ... > otherwise JSON will die because its a text delimeter

var jSonTestResultReport =
@"{ ""html"" : ""<li style=\""color:green;\"">I am text</li>"" }";


Related Topics



Leave a reply



Submit