[英]Simple CRUD using AngularJS and PHP with JSON File for Storage
在Down投票之前 (我想使用JSON文件而非數據庫來實現CRUD)
我在Angular JS中使用下面的代碼將表單數據發送到PHP,並從PHP發送我想修改本地JSON文件的表單。
我面臨以下問題
我想在用戶每次單擊注冊按鈕時追加數組
<!DOCTYPE html> <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myCtrl"> <form> <h2>Register Form</h2> <div> <label>First Name</label> <input type="text" ng-model="firstname" placeholder="First Name" required="required"> </div> <div> <label>Last Name</label> <input type="text" ng-model="lastname" placeholder="Last Name" required="required"> </div> <button ng-click='Register()'>Register</button> </form> <table> <tr> <th>First Name</th> <th>Last Name</th> </tr> <tr ng-repeat="data in usersData"> <td>{{data.firstname}}</td> <td>{{data.lastname}}</td> </tr> </table> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope, $http) { $scope.Register = function () { $http.post("misc.php", { 'firstname': $scope.firstname, 'lastname': $scope.lastname }).success(function (response) { $scope.usersData = response.users; }); }; }); </script> </body> </html>
PHP代碼
<?php
$file="misc.json";
$json = json_decode(file_get_contents($file),TRUE);
$first = $_POST['firstname'];
$last = $_POST['lastname'];
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
但是,一旦我提交,我就會在JSON文件{"":{"first":null,"last":null}}
獲得以下信息
但是我想發送真實值和我想要的JSON格式
[{
"first": "John",
"last": "Anderson"
},
{
"first": "Mike",
"last": "Langer"
}]
我可以回答您的第二個問題,即我想在用戶每次單擊注冊按鈕時追加數組
有一個名為$ scope.usernames的本地數組,當您在該成功函數中進行$ http.post調用時,將其追加到$ scope.usernames數組中。 請參考下面的代碼。
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.usernames=[];
$scope.Register = function () {
$http.post("misc.php", {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}).success(function (response) {
$scope.usernames.push({"firstname":$scope.firstname,"lastname":$scope.lastname});
$scope.usersData = response.users;
});
};
});
我早就使用過PHP,所以我首先找不到第一個錯誤,請確保它能以角度工作,然后再進行發布
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.