Hi
I was wondering what's the best "format" for the data that gets sent back to the javascript to be in? When should I use a JSON string or just plain HTML? Are there any other options besides these two?
Hi
I was wondering what's the best "format" for the data that gets sent back to the javascript to be in? When should I use a JSON string or just plain HTML? Are there any other options besides these two?
Do you want to work with the data in JavaScript and then build the DOM from that data? Use JSON strings.
Do you just want to dump something on the page in a placeholder without any logic? Use plain HTML.
json is almost always preferred, especuially if you need to do any sort of error handling. If you don't and just want to return pre-formatted HTML to place in the DOM, then returning plain HTML will suffice.
It depends on what the data being sent back is and how you plan to use it.
Pros and Cons:
Using json data and HTML generation JavaScript puts more load on the browser and less load on a server, plus no need to code presentation logic into the page which serves the data. And JSON data is usually much smaller.
Using HTML data and injecting straight into the page puts more work on the server, causes the AJAX-serving page to contain presentation logic. However, if the presentation logic is already contained in your server side code (directly or via templating language) and placing said presentation logic into JavaScript side would necessitate you to develop it from scratch, it may be a benefit instead of the downside.
In other words, use JSON data iff:
Your page will use that JSON data for purposes other than one-time generation of HTML. DUH.
Your page already contains JavaScript logic to build the HTML based on the data, or if creating such logic is very easy development cost. Especially if the opposite is true (e.g. putting the HTML generation logic server-side needs to be done and presents significant development cost).
Off-loading resource cost of converting the data into HTML from the server onto the browser is an important consideration.
JSON data is significantly smaller than the produced HTML, thus resulting in a MAJOR reduction of transmitted data. This speeds up both the server execution, AND the network transmission. We actually had like 20x speedup of a complex tree-displaying app by transmitting tree data as json instead of already-generated HTML code.
The URL producing the response can be re-used as a service for purposes OTHER than this one page, if the other possible/actual consumers would not be able to 100% re-use the HTML generated for this specific page.