由于您不了解 SQL(而且您也不会保存那么多数据),因此您可以使用 JSON 文件。此答案假设您有一台服务器(如果您打算使用 Node.js,则需要一台)。另外,我假设您想创建一个old-school high score table,带有分数和名称。
这旨在作为一般指导。您需要了解如何使用您选择的语言执行我所解释的操作。
在您的服务器中,您将有一个文件(例如 score.json),如下所示:
{
"data": [
{
"name": "Destroyer",
"score": 23
},
{
"name": "yo momma",
"score": 5
},
{
"name": "Joe",
"score": 1
},
// And so on...
]
}
此外,在您的服务器中,您还需要在特定端口上进行侦听(您可以使用 Node.js、PHP、Ruby、Python 等),您将在该端口上发出请求。这个脚本将做的是(在 JavaScript 中):
handleRequest(request) {
// Fetch your file and populate the array
var scoresTable = ...
// On request, decide which type of request it is
if (request.type === "getHighScoresTable") {
// If it wants the scores, return the json as a string
return scoresJson;
} else if (request.type === "submitScore"
&& request.score > scoresTable[scoresTable.length - 1].score) {
// Otherwise, check if the submitted score makes it into the table.
// If it does, search its position and replace.
scoresTable.forEach(function(value, index) {
if (value.score < request.score) {
scoresTable.splice(index, 0, {"name": request.name, "score": request.score});
}
});
// Trim the last element and return
scoresTable = scoresTable.slice(0, -1)
// You probably want to update your file here
}
}
现在,在您的 JavaScript 客户端文件上,当您想要保存新分数或获取高分表时,您应该向您的服务器发送一个AJAX request。 jQuery 提供了一个nicer syntax。
$.ajax({
url: 'urlToYourServer',
type: 'GET',
data: '{
"type": "submitScore",
"name": "I beat Joe",
"score": 2
}'
});
在发送之前检查客户端中的分数是否足够高可能是个好主意。此外,您可能需要考虑一些安全措施,因为任何用户都可以在执行客户请求时作弊。