【发布时间】:2015-04-28 10:49:14
【问题描述】:
我目前有一个 PHP 文件,它可以访问我的 MySQL 数据库并提取每个玩家的姓名和分数并将它们存储在一个数组中。
//This query grabs the top 10 scores, sorting by score and timestamp.
$query = "SELECT * FROM Score ORDER by score DESC, ts ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
//We find our number of rows
$result_length = mysql_num_rows($result);
//And now iterate through our results
for($i = 0; $i < $result_length; $i++)
{
$row = mysql_fetch_array($result);
echo $row['name'] . "\t" . $row['score'] . "\n"; // And output them
}
对我来说,从 PHP 文件中获取名称和分数并将它们存储在 Javascript 数组中的最佳方法是什么?
【问题讨论】:
-
$row的输出是什么? -
如下所述,使用数组返回元素。有一个 $results = array();然后在你的 for 循环中使用 array_push($results, array("name" => $row["name"], "score" => $row["score"]));最后用 json_encode($results);当您在前端获得响应时,您可以将响应数据和 JSON.parse() 转换为您可以访问的变量 parsedVariable[0].name、parsedVariable[0].score 等。
-
我在我的 Javascript 代码中添加了以下函数:
//Leaderboard $.get( "HighScores/TopScores.php", function(data) { var results = JSON.parse(data); console.log(2); results.forEach(function(result){ console.log( result.name +" - "+ result.score ); console.log(1) }); }, "json" );但我的游戏似乎没有将任何内容打印到控制台,而不是名称、分数、“1”或“2”?
标签: javascript php jquery arrays