【发布时间】:2011-02-03 22:08:59
【问题描述】:
这实际上是这个“Why need to use JSON in php and AJAX”的后续问题。
[S.1]
那么直接从 PHP 和数据库中使用 AJAX 以 HTML 格式显示数据会更慢吗?
Ex: just imagine this with AJAX but w/o JSON
PHP $query ...etc
echo "<p>".$row['name']." ".$row['comment']."</p>";
[S.2]
而不是首先使用 JSON 中的 PHP 从 db 传递数据
Ex: this with JSON and
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$comments[$x] = array("name" => $row["name"], "comment" => $row["comment"]);
}
$response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";
echo $response;
在 HTML 中显示之前
..and AJAX
// Js
$.getJSON("comments.php?jsoncallback=?", function(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
}
});
哪种方式更快?还是有任何速度差异?
Tia,希望这是一个有价值的问题,我还是 JSON 新手。
【问题讨论】:
-
我想这里唯一真正的速度差异是 JSON 的实际渲染发生在客户端(或者“创建 HTML”)。怀疑它的速度要快得多,如果有的话。