不能在 AngularJS 和 PHP 中 POST (错误 404)

Cannot POST in AngularJS and PHP (error 404)

我正在尝试将信息发送到 PHP 页面,但 returns 我收到 404 错误状态。

<form name="registerForm" novalidate>
    <div class="field"><label for="name">name : </label><input type="text" ng-model="register.registerInfo.name" name="name" id="name" autocomplete="off" required ></div>
    <div class="field"><label for="number">number : </label><input type="text" ng-model="register.registerInfo.number" name="number" id="number" autocomplete="off" required ></div>
    <br>
    <button ng-click='registerForm.$valid && register.register()'>send</button>
</form>

app.js的一部分,我正在使用ngrouting

    .controller('RegisterCtrl', ['$http', function($http){

    this.registerInfo = {
        name: '',
        number: ''
    };

    this.register = function() {
        var data = {
            name: this.registerInfo.name,
            number: this.registerInfo.number
        };

        $http.post('register.php', data).then(function(data) {
            console.log(data);
        }, function(error) {
            console.error(error);
        });
    };
}]);

register.php

<?php 

$data = json_decode(file_get_contents('php://input'));
echo 'slt';
echo $data->data->name;

http://puu.sh/m4FVO/3e607fd137.png

│   404.html
│   favicon.ico
│   index.html
│   robots.txt
│
├───images
│       yeoman.png
│
├───scripts
│   │   app.js
│   │   connection.php
│   │   register.php
│   │
│   └───controllers
├───styles
│       main.css
│       style.css
│
└───views
        contact.html
        main.html

我想发送注册信息(姓名和号码),分析 PHP 中的数据,如果可以,将它们保存到 MySQL。我不知道为什么它找不到 register.php 因为路径似乎是正确的,可能是服务器的问题?

您在 $http 中寻址 register.php,好像 register.php 脚本与您的基础 html 文件位于同一目录中。但是,您的文件列表似乎表明您的 index.html 文件位于根目录中,而 register.php 文件位于 "scripts" 子目录中。

假设您没有任何特殊的服务器端路由逻辑,您应该更新 $http 调用中的地址:

$http.post('register.php', data)

$http.post('scripts/register.php', data)



编辑:根据来自 OP

的评论添加了信息

以上答案仍然正确——原始代码错误地引用了 "scripts" 目录中的 register.php 文件。修复后,存在另一个问题。

OP 正在使用 "grunt serve";但是,grunt 服务器不会开箱即用地处理 php 文件。这是一个简单的服务器,旨在提供没有服务器端 processing/execution (php) 的静态文件(html、js、css 等)。查看此 question/answers 以了解关于 php 下的讨论:

  • Grunt serve + PHP?

但是,请考虑 installing/running 功能更全的 Web 服务器(Apache、IIS 等),尤其是当您想要在某个时候部署它时。

所以我安装了 WAMP,编辑 C:\wamp\bin\apache\apache2.4.9\conf\httpd.conf 并将 c:\wamp\www 更改为我的工作区文件夹,重新启动 wamp,我使用本地主机现在不是 localhost:9000,我必须使用绝对路径:scripts/register.php 行不通,我必须使用 http://localhost/orion/app/scripts/register.php

感谢大家的帮助。