我一直想知道如何选择使用服务器端代码还是客户端代码来构建HTML页面。我将使用一个非常简单的PHP vs javascript/jquery示例来进一步解释我的问题。非常感谢您的建议和意见。在服务器端或客户端建立网页?
假设我即将向用户展示一个网页,以在我的网页中选择一种报告类型。哪个更有意义?
对于服务器端的创作,我应该这样做:
<div id="reportChoices">
<?php
// filename: reportScreen.php
// just for the sake of simplicity, say a database returns the following rows
// that indicates the type of reports that are available:
$results = array(
array("htmlID"=>"battingaverage", "htmlLabel"=>"Batting AVG report"),
array("htmlID"=>"homeruntotals", "htmlLabel"=>"Home Run Totals report"),
);
foreach ($results AS $data)
echo "<input type='radio' name='reportType' value='{$data['htmlID']}'/>{$data['htmlLabel']}";
?>
</div>
使用客户端的代码,我得到的JavaScript构建的页面类似如下:
<!-- filename: reportScreen.html -->
<div id="reportChoices">
</div>
<!-- I could put this in the document.ready handler, of course -->
<script type="text/javascript">
$.getJSON("rt.php", {}, function(data) {
var mainDiv = $("#reportChoices");
$.each(data, function(idx, jsonData) {
var newInput = $(document.createElement('input'));
newInput
.attr("type", "radio")
.attr("name", "reportType")
.attr("value", jsonData["htmlID"])
mainDiv.append(newInput).append(jsonData["htmlLabel"]);
});
};
</script>
所有我需要在服务器上的数据转储PHP脚本,例如:
<?php
// filename: rt.php
// again, let's assume something like this was returned from the db regarding available report types
$results = array(
array("htmlID"=>"battingaverage", "htmlLabel"=>"Batting AVG report"),
array("htmlID"=>"homeruntotals", "htmlLabel"=>"Home Run Totals report"),
);
echo json_encode($results);
?>
这是一个非常简单的例子,但回回在这里,我看到了不同领域的优点和缺点。
1 - 服务器端解决方案的优点是能够隐藏大部分实际编程逻辑背后的所有内容。当用户查看页面源代码时,他们看到的只是已经建好的网页。换句话说,客户端解决方案将您所有的源代码和编程逻辑放在了如何构建特定的东西上。但是你可以使用缩小器来让你的源看起来更加神秘。
2 - 客户端解决方案将“资源负载”转移到客户端系统上(即浏览器需要使用客户端的计算机资源来构建大部分页面),而服务器端解决方案则陷入困境,服务器。
3 - 当涉及到可维护性和可读性时,客户端解决方案可能更优雅。但是,再次,我可以使用PHP库来模块化HTML控件,并使其更具可读性。
有何评论?提前致谢。
实际上,Google正在为JS内容编制索引方面迈出了重要的一步。例如,请参阅http://googlewebmastercentral.blogspot.com/2007/11/spiders-view-of-web-20.html – nico 2010-12-01 18:53:27