不幸的是,今天(2018 年 9 月)您找不到用于客户端文件写入的跨浏览器解决方案。
例如:在像 Chrome 这样的浏览器中,我们今天有这种可能性,我们可以使用FileSystemFileEntry.createWriter()编写客户端调用,但根据文档:
此功能已过时。尽管它可能在某些浏览器中仍然有效,但不鼓励使用它,因为它可以随时被删除。尽量避免使用它。
对于 IE(但不是 MS Edge),我们也可以使用 ActiveX,但这仅适用于该客户端。
如果你想跨浏览器更新你的 JSON 文件,你必须同时使用服务器端和客户端。
客户端脚本
在客户端,您可以向服务器发出请求,然后您必须读取来自服务器的响应。或者您也可以使用FileReader读取文件。对于跨浏览器写入文件,您必须有一些服务器(请参见下面的服务器部分)。
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
服务器端脚本
您可以使用很多不同的服务器,但我想写关于 PHP 和 Node.js 服务器的文章。
通过使用搜索机器,您可以找到“免费的 PHP 虚拟主机*”或“免费的 Node.js 虚拟主机”。对于 PHP 服务器,我会推荐000webhost.com,对于 Node.js,我会推荐查看和阅读此列表。
PHP服务器端脚本解决方案
用于读取和写入 JSON 文件的 PHP 脚本:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js 服务端脚本解决方案
我认为 Node.js 对初学者来说有点复杂。这不像浏览器中的普通 JavaScript。在您开始使用 Node.js 之前,我建议您阅读两本书中的一本书:
用于从 JSON 文件读取和写入的 Node.js 脚本:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Node.js 的相关链接: