将PHP数组解析为Javascript的最佳方法是什么?
问题描述:
我目前有一个PHP文件,该文件可访问我的MySQL数据库并提取每个玩家的姓名和得分并将它们存储在数组中.
I currently have a PHP file that accesses my MySQL database and pulls out the Names and Scores for each player and stores them in an array.
//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数组中的最佳方法是什么?
What is the best way for me to get both the name and the score from the PHP File and store them in a Javascript Array?
答
存储它们的最佳方法是将它们存储在json中.使用以下功能
The best way to store them is store them in json. Use following function
json_encode(arrayname);
并在html中使用
$.parsejson(responsevariable);
获取原始值.