我一直想知道如何决定在使用服务器端代码与客户端代码之间进行选择来构建
HTML页面.我将使用一个非常简单的php vs
javascript / jquery示例来进一步解释我的问题.非常感谢您的建议和意见.
假设我要向用户提供一个网页,以便在我的网页中选择一种报告.哪个更有意义?
对于服务器端创建,我会这样做:
// 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 "{$data['htmlLabel']}";
?>
使用客户端代码,我将获得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"]);
});
};
我在服务器上需要的只是一个数据转储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控件并使其更具可读性.
任何意见?提前致谢.