最简单的方法是用JavaScript读/写一个小的JSON文件


Simplest way read/write a small JSON file with JavaScript?

我的电子游戏中有一个街机风格排行榜的JavaScript对象数组。JSON是这样的:

[
    {"initials" : "JOE", "score": 20250},
    {"initials" : "ACE", "score": 10010},
    {"initials" : "YUP", "score": 5500}
]

在游戏结束时,我想将当前排行榜数组从服务器上的文件中读取到JS中,如果玩家制作了排行榜,则修改该数组并将其写回排行榜文件。

概念上很简单,但我花了一天的大部分时间阅读PHP, AJAX, jQuery,因为我是这些技术的新手,我的头有点旋转,主要是因为我找到的例子比我的要复杂得多。

什么是最简单的方法来读取JSON数组从文件到JavaScript,然后再写回来,如果JSON数组是唯一的东西在文件?我的主机服务运行PHP 5.5.

编辑:在整合了一些反馈并阅读了更多内容后,以下是我想到的,这是有效的。

// read leader board
function readLeaderboard() {
    var scores = [];
    // load json without caching
    var nonCacheableURL = 'js/leaderboard.json?nocache=' + (new   
        Date()).getTime();
    $.getJSON(nonCacheableURL, function(json) {
        for (var i=0; i<json.length; i++) {
            scores[i] = json[i];
        }
    });
    return scores;
}
// save leader board
function saveLeaderboard(leaderboard) {
    $.post('js/postLeaderboard.php', {json : JSON.stringify(leaderboard)},
        function (data, textStatus, jqXHR){}
    );
}

调用postLeaderboard.php:

<?php
file_put_contents("leaderboard.json",  $_POST['json']);
?>

在php中,您可以遵循以下行:

读取JSON并从中获取一个关联数组:

$scores = (array)json_decode(file_get_contents('scores.json'));

将数组写入JSON文件:

file_put_contents('scores.json', json_encode($scores));

我知道在PHP中最简单的方法是这样做:

// Get the Data
$data = file_get_contents("data.json");
// Decode the json in it and store it,
$decoded = json_decode($data);
// Manipulate the $decoded here...

// JSON encode the object - $decoded and store it in a variable
$modified = json_encode($decode);
// put it back in the file
/* if you want to append the data, uncomment this-
$prev = true;
*/
if(isset($prev) && $prev = true)
{
    file_put_contents("data.json", $prev . $modified);
}
else{
    file_put_contents("data.json", $modified);
}