【发布时间】:2017-10-01 18:46:25
【问题描述】:
在否决投票之前(我想使用 JSON 文件而不是数据库来实现 CRUD)
我在 Angular JS 中使用以下代码将表单数据发送到 PHP,我想从 PHP 修改我的本地 JSON 文件。
我面临以下问题
- 表单值在 JSON 文件中为 Null
-
我想在用户每次点击注册按钮时追加数组
<!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"
}]
【问题讨论】:
-
$user 未设置,Angular 传递原始数据,因此您需要在 PHP 中使用
file_get_contents('php://input')而不是 POST,或者更改提交的 Angular 表单数据。您还需要设置您的开发环境以显示所有错误。最后,您的预期输出与您从$json[$user] = array(...获得的不匹配,它会给您一个带有{ "whatever $user is": ["first": "jim", "last": "leirvik"] }的json 文件。