When we return data from an Ajax call, is it better to return a document containing HTML to display on the page or开发者_开发问答 return XML/JSON data which can be processed?
I know different circumstances may determine what 'better' means, but I really want to know which will be more appropriate for different circumstances.
I am working on the framework for a large ASP .Net application, using jQuery Ajax (forms plugin). My initial thought was to return the data as XML, then process accordingly. Then this increases processing required in Javascript, to populate the page. I am trying to balance flexible, clear and simple.
Thanks in advance for your knowledge and information.
Sometimes you will need to return only one value, other times (for example trees) you might need to return array of values with different levels.
In general, I would go with JSON.
As much as "trying to please everyone is the fast-track to mediocrity" would it not be an option to have the server-side handler for the AJAX call produce XML, JSON or HTML dependent on the value of a variable, called, for instance "format"?
This would then allow you to change the format based on the amount of data being transmitted, the intended processing (on the client-side), and provide for extensibility in the future.
For instance, for a very simple request, you may even be happy just getting a text result of "true" or "false", so you add "format=simple" to the end of the query. When requesting a list of items, JSON may be the better option, so on goes "format=json".
I am suggesting this as it seems to be one of the tricks Google offers with some of their APIs.
Depends on the situation.
1) If you want to simply fill a div tag with server-side HTML (for example for a news site of CMS), transfer HTML and put it in element.innerHTML. This is simple and effective.
2) If you have more requirements on processing the data (a dynamic client side interface, such as a grid, table, form etc) go with JSON or XML.
if your AJAX call is to grab some data, have the server return JSON to it. If it's just to get a flag, just have it return 1 or 0 or something. If you want to insert something into the page that can be more easily created on the server, have the call return some HTML.
I think it depends on how narrow is the scope of update that you are trying to make. Obviously, if the area of the page affected by the information that you get from server is something small, couple of controls that need to be updated, it's better to be brief (e.g. JSON) and do the processing client-side.
However, if the result of the server-side logic is updating huge part of the page it might be convenient to simply re-render this part server side and set it as an innerHTML of some container.
精彩评论