HTML escaping of data returned from ajax / json

I use ajax to extract some data from the backend. I get the result as json.

Then I use jquery to add it to the page:

$(...).append('<H3>' + data.title + '</H3>')

And I just realized that json data is not HTML escaped, which is bad.

What should I do?

  • Does HTML supplant all data returned from the backend in json?
  • Does all escaping in the interface do string concatenation? (i.e. wrap all external data in a shielding function)

Option 1 means that the data in json is not "correct", it is useful for HTML, but does not contain real data. And even worse, this means that I can't just use json_encode () - I would first have to go through the array data and avoid everything.

Option 2 seems more complicated, and I worry that I can skip the place. On the other hand, what do you do when you get data from SQL and build it in PHP, so I think I'm used to it.

Please do not offer:

$(...).append($('<H3></H3>').text(data.title))

This recording method becomes cumbersome when you have many levels of nested tags. I like to write HTML, not DOM.

PS. I know that I need a Javascript template library, but now I need to do this using string concatenation.

+3
source share
2 answers

Here is just a jQuery extension that adds a formatting method $append()using html escape:

(function( $ ){
  $.fn.$append = function()
  {
    var out = arguments[0];
    for (var i = 1; i < arguments.length; ++i) 
      out = out.replace("{" + arg + "}", arguments[arg].toString().htmlEscape());
    this.append(out);
  };
})( jQuery );

Using this method, you can write:

$(...).$append('<H3>{1}</H3>', data.title);

And the data will be shielded. Add salt and pepper to the above - to your taste.

: :

String.prototype.htmlEscape = function() {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
0

, . , . , http://tog2html.com

, , json obj ( var). - :

$(...).append(
   Tog('div#main_div').h1('hello, ', data.name).h3().raw(data.title).html()
   // raw() is for escaping the data into something valid to be shown in html
)

possible output:
<div id='main_div'><h1>hello, some one</h1><h3>this is my blog title</h3></div>
0

All Articles