使用推AngularJs和JavaScript数据转换成JSON文件 [英] Push data into json file using AngularJs and javascript

查看:133
本文介绍了使用推AngularJs和JavaScript数据转换成JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的角JS,并想使用AngularJs和JSON使用javascript一个CRUD形式,而无需使用任何其他服务器端语言。该脚本工作正常,但无法将数据写入到同一个目录中同一服务器上的JSON文件。我使用XAMP。这里是code:

I am new to Angular JS, and am trying to make a CRUD form using AngularJs and Json with javascript without using any other server side language. The script is working fine but is unable to write data to the JSON file on same server in same directory. I am using xamp. Here is the code :

    <!DOCTYPE html>
    <html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js">     </script>
   </head>

   <body ng-app="myapp">
     <div ng-controller="MyController" >
     <form>
       <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name <br/>
       <select ng-model="myForm.car">
         <option value="nissan">Nissan</option>
         <option value="toyota">Toyota</option>
         <option value="fiat">Fiat</option>
       </select>

       <button ng-click="myForm.submitTheForm()">Submit Form</button>
     </form>

     <div>
      {{myForm.name}}
     </div>
     <div>
      {{myForm.car}}
     </div>
   </div>

   <script>
     angular.module("myapp", [])
     .controller("MyController", function($scope, $http) {
       $scope.myForm = {};
       $scope.myForm.name = "Jakob Jenkov";
       $scope.myForm.car  = "nissan";
     console.log("Submitting form");
     $scope.myForm.submitTheForm = function(item, event) {
       console.log("Submitting form");
       var dataObject = {
          Name : $scope.myForm.name
          ,City  : $scope.myForm.car
          ,Country  : "India"
       };

       var responsePromise = $http.post("data.json", dataObject);
       responsePromise.success(function(dataFromServer, status, headers, config) {
          console.log(dataFromServer.title);
       });
        responsePromise.error(function(data, status, headers, config) {
          alert("Submitting form failed!");
       });
     }

      $http.get('data.json').then(function(data) {
    console.log(data);
  });

  });
</script>
</body>

推荐答案

您做错了。应该有你的后端一些这方面的API。您可以使用前pressjs - 这是pretty简单:

You doing it wrong. There should be some API on your backend for this. You can use expressjs - it is pretty simple:

app.post('cars/', function(req, res) {
  writeToFile('data.json', req.body); // I do not know how to write files, something like this
  res.send();
})

这篇关于使用推AngularJs和JavaScript数据转换成JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆