簡體   English   中英

使用 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 數組是文件中唯一的內容,那么將 JSON 數組從文件讀取到 JavaScript 中然后再將其寫回的最簡單方法是什么? 我的托管服務運行 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 並從中獲取 Assoc 數組:

$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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM