微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用AngularJS将数据发送到php脚本

我是AngularJS的新手,在完成一些教程后,我能够创建一个简单的页面一个简单的表单.

问题是,每次我提交表单时,似乎脚本都在发送空数据.

这是我的HTML

<div class="jumbotron text-center">
        <h1>Contatti</h1>

        <p ng-show="message">{{ message }}</p>
    </div>

<div class="row">
    <div class="col-lg-8">
        <form ng-submit="processForm()">
            <div class="form-group" ng-class="{ 'has-error' : errorName }">
                <label>Nome</label>
                <input type="text" name="name" class="form-control" placeholder="chris" ng-model="formData.name">
                 <span class="help-block" ng-show="errorName">{{ errorName }}</span> 
            </div>
            <button type="submit" class="btn btn-large">
                Salva
            </button>
        </form>
    </div>
</div>

<pre>
    {{ formData }}
</pre>

这是js:

//Creo il modulo e includo ngRoute come dipendenza
var scotchApp = angular.module('scotchApp',['ngRoute']);


//Configuro le routes
scotchApp.config(function($routeProvider){

    $routeProvider

        .when('/',{
            templateUrl: 'pages/home.html',controller: 'mainController'
        })

        .when('/chi-siamo',{
            templateUrl: 'pages/chi-siamo.html',controller: 'aboutController'
        })

        .when('/contatti',{
            templateUrl: 'pages/contatti.html',controller: 'contactController'
        });

});

//Creo il controller che gestisce la home
scotchApp.controller('mainController',function($scope){
    $scope.message = "Sono in home";
});

//Controller che gestisce la pagina chi-siamo
scotchApp.controller('aboutController',function($scope){
    $scope.message = "Sono in Chi siamo";
});


//Controller che gestisce la pagina contatti
scotchApp.controller('contactController',function($scope,$http){

    $scope.formData = {};

    $scope.processForm = function(){


        console.log($scope.formData);

        $http.post('process.PHP',$scope.formData)
             .success(
                function(data){

                    console.log(data);

                    if( data.success )
                    {
                        $scope.message = data.message;
                    }
                    else
                    {
                        $scope.errorName = data.errors.name;
                    }

                }
             );
    }
});

这是一个非常简单的PHP脚本:

<?PHP
// process.PHP

$errors = array();  // array to hold validation errors
$data = array();        // array to pass back data


// validate the variables ========
if (trim($_POST['name']) == '')
  $errors['name'] = 'Name is required.';

// return a response ==============

// response if there are errors
if ( count($errors) > 0 ) {

  // 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);

即使我在控制台的输入中写了一些数据,我得到:

Object {success: false,errors: Object}
errors: Object
name: "Name is required."
__proto__: Object
success: false
__proto__: Object

我错过了什么吗?

解决方法

你需要在PHP获取数据,

$data = json_decode(file_get_contents("PHP://input"));

$data->name  // to access name

要么

添加jquery和
改变标题,

$http({
    url: "process.PHP",method: "POST",headers: {'Content-Type': 'application/x-www-form-urlencoded'},data: $.param($scope.formData)
}).success(function(data,status,headers,config) {

}).error(function(data,config) {

});

PHP

$name= $_POST['name'];

如果你需要更改所有ajax请求的标头,那么在EX的配置块中进行,

app.config(['$httpProvider','$routeProvider',function ($httpProvider,$routeProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐