Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The AJAX response: Data (JSON, XML) or HTML snippet? [closed]

I'm just wondering what is an "ideal" output format for the AJAX response? Pure data (JSON, XML) rendered into the page using some client-side JavaScript template engine? Or an HTML snippet rendered into the page "as-is"?

What is your preference and why?

like image 835
parxier Avatar asked May 15 '09 06:05

parxier


2 Answers

In most scenarios you need to only send JSON (or XML as appropriate, I am using JSON as an example).

  • If you are sending data such as stock quotes, use JSON.
  • If you want to keep the network layer very lean then send pure JSON data and let the client do the heavy work of adding markup.
  • If the client page is persistent then send JSON. The client can then send a greeting to Person.Name. It can refresh Person.Score or show a form to edit Person.Status, all dealing with just one Person object.
  • If you are exposing web APIs, obviously use JSON so the client can do whatever they want with it.

Now that said, I really dislike generating HTML from JavaScript. It's a maintenance nightmare and I simply don't like mixing the two. So how do you avoid generating the HTML in JavaScript if all you are sending is JSON? If you are dealing with Person(s) object, when you first the render the page, you would render it as such:

...
<div class="person display">
    <div class="name"></div>
    <div class="status"></div>
    <div class="score"></div>
</div>
...

When you get the person data via AJAX, just populate the above DOM structure.

If you wish to display information for multiple Persons then instead of populating the DOM structure directly, you should make a clone of it and then populate it. This way your template stays intact and you can re-use it.

like image 142
aleemb Avatar answered Oct 28 '22 10:10

aleemb


It depends very much on what is going to use the data :

For mashup and web services

For data that will be used in your app and from outside, never use HTML : hard to parse, hard to make it fit in another structure.

If it's about few data, like some updated for a widget, use JSON because it's quick and easy to use.

If it can be a lot a data, like the result of a search query, use XML because it's more flexible for huge data analysis.

For internal use only

Don't bother using pure XML. Batch analysis will be always done before output anyway.

Most of the time, you will want to use JSON, since it's more flexible that HTML, yet fairly fast to put in place.

Use HTML if you know the data won't need to be processed afterwards and if the layout is complex. Writting complex HTML on the server side is much easier than using the DOM.

like image 23
e-satis Avatar answered Oct 28 '22 11:10

e-satis