大家好,我想在 HTML 文件中显示 MySQL 表中的数据。我有一个工作 PHP 文件:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","user","pass","db");
if (mysqli_connect_errno()) {
printf("Can't connect to SQL Server. Error Code %s\n", mysqli_connect_error($mysqli));
exit;
}
$name = $_POST['name'];
// Set the default namespace to utf8
$mysqli->query("SET NAMES 'utf8'");
$json = array();
if($result = $mysqli->query("SELECT name, device, punkte FROM freefallhighscores ORDER BY punkte DESC LIMIT 0, 50")) {
while ($row=$result->fetch_assoc()) {
$json[]=array(
'name'=>$row['name'],
'device'=>$row['device'],
'punkte'=>$row['punkte']
);
}
}
$result->close();
header("Content-Type: text/json");
echo json_encode(array( 'results' => $json ));
$mysqli->close();
?>
</body>
</html>
当我运行 PHP 文件时,我得到了预期的回声:
{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device... and so on.
现在我想在 HTML 表格中显示这些数据。为此,我必须将数据(JSON 变量)传递给 HTML 文件(也许使用 $_POST 函数?)。我怎样才能做到这一点?使用 XMLHttpRequest (XHR) 是否合适?