2016-12-01 180 views
1

使用表單,我想將數據添加到我的JSON文件。我怎樣才能做到這一點 ?我需要重新創建一個JSON文件還是可以將數據添加到我現有的JSON文件?將數據添加到JSON文件

$ http.post不起作用,所以它是一個壞的使用它或我需要更換它?

HTML文件

<body ng-app='app'>  
    <div ng-init="getData()" ng-controller="listController"> 
     <ul ng-repeat="detail in details"> 
      <li> 
       <a href="{{detail.url}}">{{detail.url}}</a> 
      </li> 
      <li> 
       {{detail.description}} 
      </li> 
      <li> 
       {{detail.author}} 
      </li> 
     </ul> 
     <form method=POST ng-submit="submit()"> 
      <label for="lien">Lien : 
       <input type="url" id="lien" ng-model="detail.url" placeholder="http://"/> 
      </label> 
      {{detail.url}} 
      <br><br> 
      <label for="description">Description : 
       <textarea id="description" ng-model="detail.description"></textarea> 
      </label> 
      {{detail.description}} 
      <br><br> 
      <label for="auteur">Auteur : 
       <input type="text" id="auteur" ng-model="detail.author"></input> 
      </label> 
      {{detail.author}} 
      <p>{{detail}}</p> 
      <input type="submit" id="submit" value="Submit" /> 
      <p>{{details}}</p> 
     </form> 
    </div> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> 
    <script src="script.js"></script> 
</body> 

JS文件

var app = angular.module("app", []); 
app.controller("listController", ["$scope","$http", 
function($scope,$http) { 
    $scope.getData = function() 
    { 
     $http.get('youtube.json').then(function (response){ 
      $scope.details = response.data;  
     }); 
    }; 
    $scope.submit = function() 
    { 
     $scope.details.push($scope.detail); 
     $http.post('youtube.json', $scope.details); 
    } 
}]); 

JSON文件

[ 
    { 
     "url": "https://www.youtube.com/watch?v=E1NIJjTYq6U", 
     "author": "Grafikart.fr", 
     "description": "Salut tout le monde" 
    }, 
    { 
     "url": "https://www.youtube.com/watch?v=fOuKMuaGJ54&list=PLjwdMgw5TTLUDlJyx4yIPQjoI-w-7Zs1r", 
     "author": "Grafikart.fr", 
     "description": "Les directives" 
    } 
] 
+0

您需要一些服務器端邏輯來保存更改。 –

+0

你應該在你的服務器上用PHP來做到這一點。退房'file_put_contents()'函數(http://php.net/manual/en/function.file-put-contents.php) –

回答

2

文件被靜態地提供在服務器上,這就是爲什麼你可以撥打$http.get('youtube.json')並有權訪問它。因此,服務器提供了一個URL供您訪問。要真正寫入它,你仍然需要一個服務器來處理請求,並寫入文件(如果它的nodejs是'fs'模塊的話)。除此之外,你不能從網絡訪問文件系統:)我希望這有助於澄清事情。

+0

好的謝謝你的回答,我將使用PHP –

+0

如果一個答案可以幫助你,你可以將它標記爲已接受:) –