【问题标题】:AngularJS send POST Request to server-side scriptAngularJS 向服务器端脚本发送 POST 请求
【发布时间】:2014-04-25 19:32:36
【问题描述】:

我正在使用 AngularJS 构建一个带有 yeoman 工具的 web 应用程序,并且无法从控制器向服务器端脚本发送 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 如何处理路由也有些困惑。我知道我可以在 app.js 文件中使用.when({ ... }) 为 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 之前添加一个“/”。您是否在开发工具中看到了发布请求?
  • 这是开发工具中的错误:POST http://127.0.0.1:9000/addUser.php 404 (Not Found)。在“addUser.php”之前添加“/”之前也是如此
  • 能不能用postman之类的工具,看看能不能发个请求到addUser.php?这应该有助于确定问题是客户端还是服务器端。
  • 我最终使用了 generator-angular-fullstack,它提供了一个用于输入路由信息的文件。

标签: javascript php angularjs http post


【解决方案1】:

尝试将 addUser.php 放入子文件夹 - /app/server/addUser.php 并执行
$http.post('server/addUser.php', $scope.user)...
php 文件也不适用于默认的生成器角度。你需要generator-angular-php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2017-05-04
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多