The AJAX response: XML, HTML, or JSON?

This is the exact question asked at quirksmode blog. There were several responses to it each with their own experiences.

I just ended up reading it because I am in the same dilemma. Ofcourse, for me it’s more of XML vs HTML. JSON is not one of the choices for my application. I initially started my ajax response as a html response but it had to evolve a bit more. Let me first explain what my requirement is. I have a bunch of markers (like on Google maps) and when the mouse is on top of a marker, I have to show the details about that marker. So, I used Ajax to do this. When the mouse is on a marker, I get the details related to only that marker. For this I used a html response and on success, just took the transport.responseText and put it into a div element.

Now, I want to support the case where I get the details of all the markers with a single response. In this case, on the client side I have to take the response, and maintain a hashmap of the details for each marker (which has a unique id). One of my preferences is to not generate the html on the client side. So, the server already formats the html. So, I had the choice of embedding the html of each marker within the xml response. But if I did this, I have to convert the dom representation of the html to a string representation which is cumbersome. So, I ended up capturing the html as cdata. The good thing with this approach is, the outer shell is an xml, but each cdata is a html string. Further, my already existing html generation code on the server side didn’t needed a fix as it wasn’t generating proper xhtml and had the html been represented as xml, I would have ended up with errors. So, the cdata representation of html saved both server-side and client-side coding.

Advertisements

1 Comment

Filed under AJAX

One response to “The AJAX response: XML, HTML, or JSON?

  1. To me the best way is to output html. Adding javascript to parse the XML response can be manipulated (thinking about security). I just let Javascript to get the string and then use innerHTML (or innerText) to display. You can also use strings with separators for multiple innerHTML dealings inside the same string. In thatcase Javascript should “explode” each chunck of html and use the innerHTML replacement inside a “for” loop. That works pretty good.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s