Php 以html格式显示SQL数据库中的数据:返回的数据对象为空

Php 以html格式显示SQL数据库中的数据:返回的数据对象为空,php,jquery,html,mysql,sql,Php,Jquery,Html,Mysql,Sql,我想从我的SQL数据库中检索数据,并在我的HTML页面上使用它 我有一个php脚本get_score.php如下: <?php $con = mysqli_connect( "localhost", "xxx1", "xxx2", "xxx3"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "SELECT `name`, `scor

我想从我的SQL数据库中检索数据,并在我的HTML页面上使用它

我有一个php脚本
get_score.php
如下:

<?php
$con = mysqli_connect( "localhost", "xxx1", "xxx2", "xxx3");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `name`, `score` FROM crossstreet ORDER BY `score` DESC LIMIT 5";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $output = ($row["name"]);
}
mysqli_free_result($result);
echo json_encode($result);

mysqli_close($con);
?>
这将返回未定义的
。如果我将其设置为
$(data)
,它将返回一个类似于此屏幕截图上的对象。

我的错误在哪里;如何从服务器获取数据以用于html

mysqli_free_result($result);
echo json_encode($result);
我认为这就是问题所在。 试着颠倒顺序。在使用之前,您将使结果免费。 这样做,而不是上述

echo json_encode($result);
mysqli_free_result($result);

您需要使
$output
成为一个数组,以便获得所有行

$output = array();
while ($row = mysqli_fetch_assoc($result)) {
    $output[] = $row['name'];
}
那么你应该回应这一点:

echo json_encode($output);

在jQuery代码中,应该执行
console.log(数据)

您需要
json\u编码($output)
而不是
$result
$result
发送到客户端是没有用的。
echo json_encode($output);