0

My jQuery function is making a ajax call (GET request) and it has to return HTML that I will then inject in the page in the success event.

What do I have to escape in the HTML to ensure there aren't any issues?

apaderno
  • 28,547
  • 16
  • 75
  • 90
loyalflow
  • 14,275
  • 27
  • 107
  • 168
  • 4
    Well, if the intention is the get HTML an display it on the page, why do you want to escape it? Are you trying to render the results as HTML, or display the HTML as text? – vcsjones Jun 25 '12 at 16:05
  • I agree, if your returning HTML, you don't need to escape anything? – Liam Jun 25 '12 at 16:06
  • 1
    Well, we need more information. Also, how much do you trust the HTML being generated? For example, are you sure it is safe, or did the user type it into a text input? – Justin Ethier Jun 25 '12 at 16:07
  • I am control of the ajax call and the html returned. I just assumed that the html would have to be escaped to work in javascript. I want to render the html in the webpage. – loyalflow Jun 25 '12 at 16:26
  • See this SO on escaping HTML w/ jQuery: http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery – pixelbobby Jun 25 '12 at 16:33

1 Answers1

0

Look up jQuery's load method, this will do everything you want without the extra parsing.

From Visual jQuery (www.visualjquery.com):

In jQuery 1.2 you can now specify a jQuery selector in the URL. Doing so will filter the incoming HTML document, only injecting the elements that match the selector. The syntax looks something like "url #some > selector". See the examples for more information.

Returns: jQuery

Parameters:

url (String): The URL of the HTML page to load. data (Map): Key/value pairs that will be sent to the server. callback (Callback): The function called when the ajax request is complete (not necessarily success). function (responseText, textStatus, XMLHttpRequest) {
this; // dom element } Example

Load a piece of the documentation sidebar navigation into a custom unordered list.

jQuery Code

$("#links").load("/Main_Page #p-Getting-Started li");

The example given will load the url /Main_Page, extracting the contents inside each LI inside the ID p-Getting-Started, and insert them directly into the ID 'links' in your page.

I use this technique in conjunction with Modernizr to load up product pages in a popup "window" inside my web app if the browser is not a mobile browser. Less than 20 lines of JS/jQuery code makes the web site more interactive for its desktop users. Be sure to explore the options the load() method has, you can limit results and it also has a success callback.

Derreck Dean
  • 3,708
  • 1
  • 26
  • 45