Return HTML in PHP JSON response

I am building an app to save small notes and comments. The app will require from you to submit a title and it will provide you a text area for your text.

Until now when you submit a title I create with jquery a title - text area pair for you to type your text.

I was thinking to return the pair through JSON, but someone told me that this is bad practice.

Is it really bad practice to return HTML through Jason and why?


JOSN was made to overcome the bulky XML format used for data exchanging. It really is a light weight data-exchange format as described by James. Suppose: You need to display a dynamic list of products having all the info related to a product. If you return full HTML in the JSON its size is 2048 characters. But if you only return product name and realted info without the HTML markup then the response text string size will be less than 2048 characters, it can be 100 characters only because you are omitting the HTML markup which is not really required. SO you can just have the light-weight version of the data and then insert it in the HTML markup using client side script. This will make your application faster because you will have to wait less for the server response as the data size is small and transferring small amount of data(characters) will always be quicker than large data(characters).

XML contained heavy markup therefore JSON was looked as an alternative for faster data transfer.


JSON (JavaScript Object Notation) is a lightweight data-interchange format http://www.json.org/

The HTML DOM structure should be created and use JSON for exchanging data.

Once you've retrieved the data creating dynamic dom elements is fair game.


A few closely related questions:

Why is it a bad practice to return generated HTML instead of JSON? Or is it?

How dangerous is it send HTML in AJAX as opposed to sending JSON and building the HTML?

As far as I know, it's not bad practice to return a HTML string within a JSON object. The accepted answer for that second question seems to agree:

Request and return JSON for large datasets, but include the (escaped) HTML snippet for each record in the JSON record. This means more rendering time and more bandwidth use than (2), but can reduce duplication of often complex HTML rendering.

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

上一篇: jquery,在滚动时在某个位置找到div类名

下一篇: 在PHP JSON响应中返回HTML