我对角度相对较新,并且遵循从表单向php页面发布数据的简单教程。我获得了成功的回调,我可以在console.log中获取表单数据。但是我得到一个空的post数组。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script>
// Defining angularjs application.
var postApp = angular.module('postApp', []);
// Controller function and passing $http service and $scope var.
postApp.controller('postController', function ($scope, $http) {
// create a blank object to handle form data.
$scope.user = {};
// calling our submit function.
$scope.submitForm = function () {
// Posting data to php file
$http({
method: 'POST',
url: 'clone.php',
data: $scope.user, //forms user object
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function (data) {
if (data.errors) {
// Showing errors.
$scope.errorName = data.errors.name;
$scope.errorUserName = data.errors.username;
$scope.errorEmail = data.errors.email;
console.log('failure');
} else {
$scope.message = data.message;
console.log('success');
}
});
};
});
</script>
</head>
<body ng-app="postApp" ng-controller="postController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<div class="page-header">
<h1>Post data using angularJS</h1>
</div>
<!-- FORM -->
<form name="userForm" ng-submit="submitForm()">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="user.name">
<span ng-show="errorName">{{errorName}}</span>
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username">
<span ng-show="errorUserName">{{errorUserName}}</span>
<span ng-show="message">{{message}}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email">
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</body>
</html>
<?php
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
// checking for blank values.
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['username']))
$errors['username'] = 'Username is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (!empty($errors)) {
$data['errors'] = $errors;
} else {
$data['message'] = 'Form data is going well';
}
// response back.
echo json_encode($data);
echo $_POST['username'];
?>