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?
In most scenarios you need to only send JSON (or XML as appropriate, I am using JSON as an example).
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.
It depends very much on what is going to use the data :
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With