简体   繁体   中英

Push data into json file using AngularJs and javascript

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>

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();
})

我认为您无法将任何内容发布到json文件,因为它只是文件,而不是服务器上的任何内容(API URL)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM