javascript - 想要使用 Angular 将表单中的数据作为 JSON 数组中的新对象提交

标签 javascript json angularjs node.js

我希望创建一个带有提交按钮的简单输入框,该按钮会将信息添加到 JSON 文件中。我使用 Angular 检索该数据,创建一个新的 JSON 对象,并将该对象与新数据一起发布到名为 pets.json 的文件中。

HTML

<form ng-submit="submit()" ng-controller="PetPosting">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>

AngularJS

  var app = angular.module('app', ['ui.bootstrap', 'bootstrapLightbox']);

 //load images from pets.json and display them in HTML
 app.controller('GalleryCtrl', function ($scope, Lightbox, $http) {
     $http.get('pets.json')
     .then(function(res){
      $scope.images = res.data;
   });
 });
 /*Add new data to JSON file*/
 app.controller('PetPosting',function($scope, $http) {

      $scope.submit = function() {
        if ($scope.text) {
          $http({
                    method: "post",
                    url: "pets.json",
                    data: {
                      "thumbUrl": $scope.text,
                    }
                });
        }

      }



});

我不完全理解这是如何工作的。任何有关如何弄清楚如何完成这项简单任务的见解或指导将不胜感激:)

最佳答案

这不是“$http”的正确实现,“url”属性是接收您的数据的服务器端点,因为您需要一些服务器端代码来附加到 .json 文件。

如果您想将信息保存在用户本地,LocalStorage API 可能就足够了,而且很容易实现

关于javascript - 想要使用 Angular 将表单中的数据作为 JSON 数组中的新对象提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728464/

相关文章:

javascript - 使用 jQuery 的 $.ajax() 或 $.getScript() 方法时有什么方法可以识别重定向吗?

ios - JSON 查询不起作用

angularjs - 使用 AngularJS 在一页上使用多个 4.2 CKEditor 实例

Javascript 从 json 创建复杂的表头

angularjs - 如何在具有多个类的 Protractor 中选择一个元素?

javascript - AngularJS 是否错误地解析了值?

javascript - 将 IBM watson API 与 jquery 的 $.ajax 一起使用

Javascript - 创建新对象,但不传递任何参数

javascript - JavaScript 中判断对象是否具有属性的两种方法

json - 搜索 JSON 文件 bash