AngularJS将POST请求发送到服务器端脚本

时间:2014-04-25 19:32:36

标签: javascript php angularjs http post

我正在使用AngularJS使用yeoman工具构建webapp,并且无法从控制器向服务器端脚本发送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文件与index.html一起位于app /目录中。关于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);

1 个答案:

答案 0 :(得分:1)

尝试将addUser.php放到子文件夹 - /app/server/addUser.php并执行
    $ http.post('server / addUser.php',$ scope.user)...
此外,php文件无法使用默认的generator-angular。您需要generator-angular-php

相关问题