当我有一个有趣的问题时,我一直在做很多事情,包括发出 AJAX 请求以从我的网站后端获取信息。是在 php 中进行 html 样式设置,然后发送到客户端更好,还是将数据作为 json 发送,然后在 javascript 中设置样式更好?
由于这个问题有点模糊,我将举一个例子:
<?php
$data = array();
$data[0] = array("username" => "Supericy", "content" => "just a sample message 1");
$data[1] = array("username" => "Supericy", "content" => "just a sample message 2");
$data[2] = array("username" => "Supericy", "content" => "just a sample message 3");
// etc...
// now this is the choice:
if ($json)
{
return json_encode($data);
}
else
{
// or
$returnString = "";
for (...)
{
$returnString .= '<div class="username">' . $data[i]["username"] . '</div>';
$returnString .= '<div class="content">' . $data[i]["content"] . '</div>';
}
return $returnString;
}
?>
然后在我的javascript中:
// get the information as raw json
var data = ajax_request(json = true);
var author = document.createElement('div');
author.className = "author";
author.innerHTML = data[i]["username"];
var content = document.createElement('div');
content.className = "content";
content.innerHTML = data[i]["content"];
body.appendChild(author);
body.appendChild(content);
// -- OR --
// get the information as pre-formated html
var data = ajax_request(json = false);
body.innerHTML += data;