是否可以只用 angular 将数据写入本地 json 文件? [英] Is it possible to write data to a locally json file with nothing but angular?
问题描述
在仅使用 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 = '数据已保存';});};};
html:
未创建 sample_data.json,如果我创建一个空文件,它也不会填充数据.$scope.model 肯定包含数据.如果有人可以提供帮助,将不胜感激.谢谢,阿隆.
是否可以只用 angular 将数据写入本地 json 文件?
没有.即使您从本地文件系统(例如,file://myfile.html
)或本地网络服务器(例如,http://localhost/myfile.html)运行页面.html
或 http://host-on-my-intranet/myfile.html
),您仍然无法直接从浏览器托管的 JavaScript 代码写入文件.>
两种选择:
将它发送到可以写出它的东西(例如,服务器),或者
将其提供为
data:
URI(如果在您的情况下可行),用户可以右键单击并选择另存为..."以下是为某些 JSON 文本创建
data:
URI 的方法:var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(theJSON);
#2 的完整示例:
var theData = {foo: "酒吧"};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 = "右键单击并选择'另存为...'";document.body.appendChild(a);
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:
function onSubmit() {
$scope.save = function() {
$http.post('./temp/sample_data.json', JSON.stringify($scope.model)).then(function(data) {
$scope.msg = 'Data saved';
});
};
};
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.
Is it possible to write data to a locally json file with nothing but angular?
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.html
or http://host-on-my-intranet/myfile.html
), you still have no means of directly writing to a file from browser-hosted JavaScript code.
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);
Full Example of #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);
这篇关于是否可以只用 angular 将数据写入本地 json 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!