开发者

Benefit of outputting JSON as opposed to plain HTML

Just wondering which is best here. I want to output data from a table in my DB then put a lot of this data into a html table on the fly on my page. I'm working with Java on the server side. B开发者_如何学运维asically I pull the results form the DB and have the raw data..just what next?

There is a chance I may want to take data from multiple tables in order to combine it into one table for my site.

I retrieve the results of the query from the DB, now do I create a text from it in the form of json which I can parse as json using jquery upon the return of the object to my browser?(kind of a sub question of this question: Is just using a stringbuilder the correct way to make a json object to output?)

Or..

Should I build the HTML as a string and output that to the browser instead?

Which is better and why?


I've built entire pages from JSON data on the client. It reduces the redundancy of repeating HTML and can lead to better performance, depending on the complexity of your HTML.

I had large a catalog that used multiple tabs for different sections. Sending it all to the client as JSON and generating the resulting HTML was way faster than downloading the equivalent HTML.

What you lose, of course, is SEO. Search engines won't be able to see the Javascript-generated output. There are ways around this, using hash URL techniques.


I used to be in favor of generating HTML on the server so that the client can be dumb and simply inject dynamic content. The pragmatic real world advantages for our small team was that we needed to be experts at fewer different technologies. We focused on the middle tier and back end and spent less time on the front end.

Lately, with tools like jQuery, it is easier and easier to do more robust client stuff without having to increase the dev bandwidth much. From a client side, I can say building dynamic HTML from JSON using jQuery isn't that hard.

From the server side, I'm sure there are tools to serialize to JSON. I wouldn't roll your own with StringBuilder. Sorry, I'm not a Java guy so don't have a recommendation.


I'd go with JSON if I knew I had anything more than just static views of the data in mind later on.

But if it's just so that you can see what the result was, and don't care too much for the data then I'd go with the straight forward HTML output.


For actually generating the JSON server-side, there are a number of libraries you can use. org.json is the canonical one, but I prefer Stringtree personally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜