0
我正在使用AngularJS與yeoman工具構建webapp,並且無法從控制器向服務器端腳本發送POST請求。以下是我的控制器代碼中的功能:AngularJS向服務器端腳本發送POST請求
$scope.addUser = function() {
$http.post('addUser.php', $scope.user).success(function(response) {
console.log('success');
console.log(response);
$scope.showForm = false;
$scope.infoSubmitted = true;
}).error(function(err){
console.log('failure');
console.log(err);
});
};
addUser.php文件位於app /目錄以及index.html中。對於AngularJS如何處理路由,我也有點困惑。我知道我可以用.when({ ... })
爲app.js文件中的GET請求定義路由,但我看不到如何處理POST請求並調用服務器端腳本。
這是PHP文件我想連接到:
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
// return a response ===========================================================
// response if there are errors
if (! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
我建議你添加關於錯誤的完整信息(來自Firebug或同等版本);那麼甚至可能是PHP文件。 –
嘗試在addUser.php之前拋出「/」。您是否在開發工具中看到了發佈請求? – Trent
這是開發工具中的錯誤:'POST http://127.0.0.1:9000/addUser.php 404(Not Found)'。這是相同的,然後我在「addUser.php」之前添加「/」 – mattr