javascript - $http.put 可以将数据写入 JSON 文件吗

标签 javascript json angularjs angular-http

对于这个新手问题,我深表歉意,但我在网上搜索时得到了相互矛盾的答案。

我已经创建了一个 AngularJS 应用程序来使用 $http.get 从 JSON 文件中读取并将数据显示为一个表单,每个表单元素都与 ng-model 绑定(bind)。理想情况下,我希望用户能够编辑所需的字段并单击保存,然后在 JSON 文件中更新该数据。有人告诉我,要做到这一点,您需要一个像 NodeJS 这样的第三方服务器,但我看到其他示例显示它在视频中完成。有人可以告诉我这是否可以在没有第 3 方服务器的情况下实现,如果可以,最好的做法是什么。

谢谢

最佳答案

$http GET(对于位于客户端的资源)将无法与 Chrome 浏览器一起使用,并且会出现 CORS 错误(除非您通过使用 run .../chrome.exe 打开 Chrome 来禁用 Chrome 网络安全"--allow- file-access-from-files -disable-web-security)。Firefox 给出一个错误,指出 JSON 格式不正确,即使它是。浏览器似乎不喜欢它。

HTML5 LocalStorage 是您希望执行 CRUD 操作并让数据在页面刷新后继续存在的客户端存储的最佳选择。一个很好的例子是 [TodoMVC 示例] ( https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/angularjs )

显示了一个非常简单的示例,将 json 文件保存到 localstorage 并读取 localstorage 的内容。该服务包含与本地存储交互的 getter 和 setter 方法。

INDEX.HTML

<body ng-app = "app">
<div ng-controller="MainCtrl">
  <form>
<input placeholder="Enter Name.." ng-model="newContact"/>
<button type="submit" class="btn btn-primary btn-lg"    
       ng-click="addContact(newContact)">Add
    </button>
  </form>
  <div ng-repeat="contact in contacts track by $index">
    {{contact.name}}
  </div>
</div>

APP.JS

angular.module('app', ['app.services'] )
.controller('MainCtrl', function ($scope, html5LocalStorage) {
    //create variable to hold the JSON
var contacts = $scope.contacts = html5LocalStorage.get();
$scope.addContact = function(contact) {     
  $scope.contacts.push( {"name":contact} ); //Add new value
  html5LocalStorage.put($scope.contacts);   //save contacts to local storeage
    }
});

SERVICES.JS

angular.module('app.services', [] )
.factory('html5LocalStorage', function () {
  var STORAGE_ID = 'localStorageWith_nG_KEY';   //the Local storage Key
    return {
    //Get the localstorage value
    get: function () 
    {
        return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
    },
    //Set the localstorage Value
    put: function (values) 
    {
        localStorage.setItem(STORAGE_ID, JSON.stringify(values));
    }
  };
});

否则,您可以使用 Node 和 Express 并将 JSON 文件存储在服务器上。使用文件系统模块“fs-extra”与 json 文件交互。 您必须为客户端创建 RESTful API 路由,以便使用 $http 与服务器交互并执行 CRUD 操作。

  • /放
  • /得到
  • /删除
  • /发布

关于javascript - $http.put 可以将数据写入 JSON 文件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920994/

相关文章:

javascript - angularjs 多个复选框过滤

javascript - 按字母顺序排列 JavaScript for 循环

javascript - 将键值动态添加到 Javascript 中的嵌套对象

java - GSON - 转换字符串不区分大小写

java - 如何从 Jackson ObjectMapper 中排除空对象?

AngularJS/Karma - 指令中的单元测试功能

javascript - Angular 条件

php - 通过超链接传递数据而不在 URL 中包含数据

javascript - 在哪里发布代码以供开源使用?

javascript - 为开发构建 webpack 时出现语法错误