使用JQuery或其他类似框架从自定义url /Web服务加载HTML内容非常容易。到目前为止,我已经多次使用这种方法,并发现性能令人满意。

但是所有的书,所有的专家都试图让我使用JSON而不是生成的HTML。它为什么比HTML更优越?

它会快很多吗? 它在服务器上的负载是否非常小?

另一方面,我有一些使用生成HTML的理由。

它是简单的标记,通常和JSON一样紧凑,甚至更紧凑。 它更不容易出错,因为你得到的都是标记,而不是代码。 在大多数情况下,编程会更快,因为你不必为客户端单独编写代码。

你站在哪一边,为什么?


当前回答

IMV, it's all about separating the data from the presentation of the data, but I'm with Pascal, it doesn't necessarily follow that that separation can only be across the client/server boundary. If you have that separation already (on the server) and just want to show something to the client, whether you send back JSON and post-process it on the client, or just send back HTML, depends entirely on your needs. To say you're "wrong" to send back HTML in the general case is just far too blanket a statement IMV.

其他回答

发送json通常是在javascript小部件从服务器请求信息时完成的,比如列表、树视图或自动补全。这是当我将发送JSON,因为它是数据,将被解析和使用原始。然而,如果你只是要显示HTML,那么在服务器端生成它并在浏览器上显示它就会少很多工作。浏览器在使用innerHTML = ""直接将HTML插入dom时进行了优化,所以这样做不会出错。

我主要同意这里的观点。我想总结一下:

如果您最终要在客户端解析HTML以对其进行一些计算,那么发送HTML是一种糟糕的做法。 如果您最终所做的只是将JSON合并到页面的DOM树中,那么发送JSON是一种糟糕的做法。

这取决于具体情况。

有时,避免使用JSON是必要的。 例如,当我们的程序员在用js编程时遇到困难。

我的经验告诉我:使用ajax服务比使用内联JSON更好。

迟早js会成为一个问题

HTML有许多冗余和不显示的数据,即标签,样式表等。 因此,与JSON数据相比,HTML的大小会更大,导致更多的下载和渲染时间,也会导致浏览器忙于渲染新数据。

IMV, it's all about separating the data from the presentation of the data, but I'm with Pascal, it doesn't necessarily follow that that separation can only be across the client/server boundary. If you have that separation already (on the server) and just want to show something to the client, whether you send back JSON and post-process it on the client, or just send back HTML, depends entirely on your needs. To say you're "wrong" to send back HTML in the general case is just far too blanket a statement IMV.