简体   繁体   English

将PHP数组解析为Javascript的最佳方法是什么?

[英]What is the best way to Parse a PHP Array into Javascript?

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. 我目前有一个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
}

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? 对我来说,从PHP文件中获取名称和分数并将它们存储在Javascript数组中的最佳方法是什么?

The best way to store them is store them in json. 最好的存储方式是将它们存储在json中。 Use following function 使用以下功能

json_encode(arrayname);

and in html use 并在html中使用

$.parsejson(responsevariable);

to get original value. 获得原始价值。

我建议将json_encoded数组提供给javascript变量(json_encode()),并使用javascript json解码功能,这样您将得到想要的结果:)

Create a result variable 创建一个结果变量

$results = array();

Store your results in it in your loop 将结果存储在循环中

array_push($results, array("name" => $row["name"], "score" => $row["score"]));

At the end return it with 最后返回

echo json_encode($results);

When you get the response on the front end, you can take the response data and JSON.parse() it to turn it into a variable that you can access 在前端获得响应时,可以获取响应数据并使用JSON.parse()将其转换为可以访问的变量

var results = JSON.parse(data);

results.forEach(function(result){
    console.log( result.name +" - "+ result.score );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM