开发者

HTML-escaping the data returned from ajax/json

I'm using ajax to retrieve some data from the backend. I get the result as json.

I then use jquery to add it to the page:

$(...).append('<H3&g开发者_开发百科t;' + data.title + '</H3>')

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

What should I do?

  1. HTML escape all the data returned from the backend in the json?
  2. Do all the escaping on the frontend when concatenating strings? (i.e. wrap all external data in an escaping function)

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

Option 2 seems more complicated, and I'm worried I may miss a spot. On the other hand that's what you do when getting data from SQL and building it in PHP, so I guess I'm used to it.

Please do not suggest:

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

That method of writing becomes unwieldy when you have many levels of nested tags. I like to write HTML, not DOM calls.

PS. I know I need a Javascript templating library, but for right now I need to do it with string concatenation.


Here is simple jQuery extension that adds $append() formatting method with html escapement:

(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 );

With this method you can write:

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

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

Update: You will also need this:

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


Well, I am sort of working on an open-source project on my weekends. I think it would fit your demand. Please check it out at http://tog2html.com

For instance, in your case , after getting a json obj (var data). You can do something like :

$(...).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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜