【发布时间】: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