Javascript 是否可以只用 angular 将数据写入本地 json 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30288087/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to write data to a locally json file with nothing but angular?
提问by Alon Weissfeld
I'm trying to write data to a json file after hitting "Submit" on an html formly-form using only angular, but nothing is happening. I know I can read a json file using angular but not sure on creating files. onSubmit() in controller:
在仅使用 angular 的 html formly-form 上点击“提交”后,我试图将数据写入 json 文件,但没有任何反应。我知道我可以使用 angular 读取 json 文件,但不确定创建文件。控制器中的 onSubmit():
function onSubmit() {
    $scope.save = function() {
        $http.post('./temp/sample_data.json', JSON.stringify($scope.model)).then(function(data) {
            $scope.msg = 'Data saved';
        });
    };
};
html:
html:
<form name="form" ng-submit="onSubmit()" novalidate>
    <formly-form model="model" fields="fields"></formly-form><br/>
    <button type="submit">Submit</button>
</form>
The sample_data.json isn't created and if I create an empty file it does not fill up with the data as well. The $scope.model defenitly contains data. If anyone can help, it will be very appreciated. Thanks, Alon.
sample_data.json 未创建,如果我创建一个空文件,它也不会填充数据。$scope.model 肯定包含数据。如果有人可以提供帮助,将不胜感激。谢谢,阿隆。
采纳答案by T.J. Crowder
Is it possible to write data to a locally json file with nothing but angular?
是否可以只用 angular 将数据写入本地 json 文件?
No. Even if you're running the page from the local file system (e.g., file://myfile.html) or from a local webserver (e.g., http://localhost/myfile.htmlor http://host-on-my-intranet/myfile.html), you still have no means of directly writing to a file from browser-hosted JavaScript code.
不可以。即使您从本地文件系统(例如file://myfile.html)或本地网络服务器(例如http://localhost/myfile.html或http://host-on-my-intranet/myfile.html)运行页面,您仍然无法从浏览器托管的 JavaScript 代码直接写入文件。
Two choices:
两种选择:
- Send it to something (e.g., a server) that can write it out, or 
- Provide it as a - data:URI (if feasible in your case) that the user can right-click and choose "save as..."- Here's how you create a - data:URI for some JSON text:- var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
- 将它发送到可以写出它的东西(例如,服务器),或者 
- 将其作为 - data:URI(如果在您的情况下可行)提供,用户可以右键单击并选择“另存为...”- 以下是 - data:为某些 JSON 文本创建URI 的方法:- var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
Full Exampleof #2:
#2 的完整示例:
var theData = {
  foo: "bar"
};
var theJSON = JSON.stringify(theData);
var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
var a = document.createElement('a');
a.href = uri;
a.innerHTML = "Right-click and choose 'save as...'";
document.body.appendChild(a);回答by Quentin
No.
不。
Angular runs client side.
Angular 运行客户端。
If you want to write data to the server (even one on the same computer as the browser) then you need server side code to do it.
如果您想将数据写入服务器(甚至与浏览器在同一台计算机上),那么您需要服务器端代码来执行此操作。
回答by Alex McMillan
You can't access the local filesystem (directly) from Javascript. This is enforced for security reasons (and makes sense when you think about it!).
您无法从 Javascript 访问本地文件系统(直接)。这是出于安全原因强制执行的(当您考虑时,这是有道理的!)。
回答by Jason Sebring
Since this is not possible you could try another route. Your $scope.save was not being invoked by the way, only assigned.
由于这是不可能的,您可以尝试另一条路线。你的 $scope.save 没有被调用,只是被分配了。
$scope.save = function() {
  localStorage.model = JSON.stringify($scope.model);
};
function onSubmit() {
  $scope.save();
  $scope.msg = 'saved';
};
To get your model back do this on init:
要让您的模型恢复,请在 init 上执行此操作:
if (localStorage.model)
  $scope.model = JSON.parse(localStorage.model);
回答by AnthonyW
The following code adds a download button for a JSON object.
以下代码为 JSON 对象添加下载按钮。
Note:wrapping a button with an anchor tag is not recommended for HTML 5 yet it works in Chrome which is all I needed. YMMV.
注意:不建议在 HTML 5 中使用锚标记包装按钮,但它可以在 Chrome 中运行,这正是我所需要的。天啊。
HTML:
HTML:
<a download="my-json-object.json" [href]="dataUri">
  <button>Download</button>
</a>
Typescript:
打字稿:
  get dataUri(): SafeUrl {
    const jsonData = JSON.stringify(this.dataSource);
    const uri = 'data:application/json;charset=UTF-8,' + encodeURIComponent(jsonData);
    return this.sanitizer.bypassSecurityTrustUrl(uri);
  }

