首先,我强烈建议在 ajax 请求中使用 JS 对象作为数据变量。当您拥有大量数据时,这将使您的生活变得更加简单。例如:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: { "code": code },
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
至于从服务器获取信息,首先您必须编写一个 PHP 脚本来从数据库中提取数据。如果您想从服务器获取大量信息,那么您可能还想以 XML 或 JSON 格式序列化您的数据(我会推荐 JSON)。
在您的示例中,我假设您的数据库表非常小且简单。可用的列是 id、code 和 description。如果您想提取特定代码的所有新闻描述,您的 PHP 可能看起来像这样。 (我有一段时间没有做任何 PHP 了,所以语法可能是错误的)
// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
private $id = null;
var $code = null;
var $description = null;
function setID($id) {
$this->id = $id;
}
function setCode($code) {
$this->code = $code;
}
function setDescription($desc) {
$this->description = $desc;
}
}
// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to
// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));
// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);
// get the data
while ($result = mysql_fetch_assoc($query)) {
$data = new NewsDB();
$data.setID($result['id']);
$data.setCode($result['code']);
$data.setDescription($result['description']);
// append data to the array
array_push($data_array, $data);
}
// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);
样本输出:
[
{ "code": 5, "description": "desc of 5" },
{ "code": 6, "description": "desc of 6" },
...
]
所以在这个阶段,您将拥有一个以 JSON 格式返回数据的 PHP 脚本。还假设这个 PHP 脚本的 url 是foo.php。
然后您可以简单地通过以下方式从服务器获取响应:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "foo.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
// do something with data
for (var i = 0, len = data.length; i < len; i++) {
var code = data[i].code;
var desc = data[i].description;
// do something
}
});
});
就是这样。