Do you Ajax JSON or HTML?

What is the preferred way to do AJAX.

If it was for a search page written in PHP using Jquery for the AJAX

How would you handle the response

a) Have the response contain all the relevant html/styling

or

b) Send pure JSON and have a javascript function build the html/styling around the javascript variables.

I can see advantages to both. 'a' is obviously easier whilst 'b' is more efficient (although gzip would probably make the difference negligible).


I would say 'a' is the option you mostly want to stick with.

It's much easier to keep consistent templates server side (you can reuse them in non AJAX scenarios).

Client-side Templating isn't super elegant (if you're going to do it i suggest this: http://ejohn.org/blog/javascript-micro-templating/)

In terms of the styling I would include a minified stylesheet when the page loads not when loading the content.


I would go with the html:

  • doing the conversion from json to html will make the client slower (and you don't know anything about the performance of the user's client)
  • doing it in json means you have to convert twice (from your server's data structure to json, then from json to html)
  • you probably do rendering to html already on the server, so you have the infrastructure
  • network traffic difference will be negligable
  • you can use libraries that do all the work for you (eg with JQuery, an ajax call that returns html just becomes jQuery('#div').load(url)).

  • Personally, I mostly return snippets of HTML from ajax calls, unless I need to do something with the returned data programmatically. For example:

  • Autocomplete functionality. Return a JSON array of data, use javascript to create the appropriate elements.
  • Anything that doesn't really request data, but actually posts it. In-line editing comes to mind. I usually return a status message in JSON format.
  • That being said, obviously I feel that both options are valid. I'm sure purists will disagree, but sometimes returning plain ol' HTML is good enough.

    链接地址: http://www.djcxy.com/p/47886.html

    上一篇: 什么更快? Ajax加载JSON或Ajax加载完成输出

    下一篇: 你是Ajax JSON还是HTML?