title: HTML-escaping the data returned from ajax/json
body: <p>I'm using ajax to retrieve some data from the backend. I get the result as json.</p>
  
  <p>I then use jquery to add it to the page:</p>
  
  <pre><code>$(...).append('&lt;H3&gt;' + data.title + '&lt;/H3&gt;')
  </code></pre>
  
  <p>And I just realized that the json data is not HTML escaped, which is bad.</p>
  
  <p>What should I do?</p>
  
  <ol>
  <li>HTML escape all the data returned from the backend in the json?</li>
  <li>Do all the escaping on the frontend when concatenating strings? (i.e. wrap all external data in an escaping function)</li>
  </ol>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Please do not suggest:</p>
  
  <pre><code>$(...).append($('&lt;H3&gt;&lt;/H3&gt;').text(data.title))
  </code></pre>
  
  <p>That method of writing becomes unwieldy when you have many levels of nested tags. I like to write HTML, not DOM calls.</p>
  
  <p>PS. I know I need a Javascript templating library, but for right now I need to do it with string concatenation.</p>