【问题标题】:Display data from SQL database in html: returned data object empty在 html 中显示来自 SQL 数据库的数据:返回的数据对象为空
【发布时间】:2015-08-08 00:31:24
【问题描述】:

我想从我的 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);
?>

然后我想通过 JQuery 检索数据。我已阅读有关跨域问题的信息,但我检索的数据和 html/Jquery 在同一台服务器上。

$.get("get_score.php", function( data ) {
  console.log(window[data]);
}, "json" );

这将返回 undefined。如果我将其设为$(data),它将返回一个类似于此屏幕截图中的对象。

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

【问题讨论】:

  • 你需要json_encode($output) 而不是$result

标签: php jquery html mysql sql


【解决方案1】:

您需要将$output 设为一个数组,以便获得所有行。

$output = array();
while ($row = mysqli_fetch_assoc($result)) {
    $output[] = $row['name'];
}

那么你应该回应这个:

echo json_encode($output);

在你的 jQuery 代码中,你应该使用console.log(data);

【讨论】:

    【解决方案2】:
    mysqli_free_result($result);
    echo json_encode($result);
    

    我认为这是问题所在。 尝试颠倒顺序。在使用它之前,您正在免费提供结果。 这样做,而不是上面的。

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

    【讨论】:

    • $result 发送给客户端没有用处。
    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多