将数据发送到AngularJS PHP脚本 [英] Send data to a php script with AngularJS

查看:149
本文介绍了将数据发送到AngularJS PHP脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AngularJS新和以下一些教程,我能够创建一个简单的页面和一个简单的形式。

I'm new in AngularJS and following some tutorials I was able to create a simple page and a simple form.

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

The problem is that every time I submit the form seems that the script is sending empty data.

这是我的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脚本:

and this is a very simple php script:

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

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

Even if I write some data in my input in the console I get:

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

我缺少的东西吗?

Am I missing something?

推荐答案

您需要获取数据PHP作为,

you need to get the data in php as,

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

$data->name  // to access name


添加jQuery和
更改页眉,

add the jquery and change the headers,

$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, status, headers, config) {

});

PHP

$name= $_POST['name'];


如果您需要更改所有Ajax请求的头,然后做它在配置块EX,


if you need to change the headers of all ajax requests then do it in config block for EX,

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

这篇关于将数据发送到AngularJS PHP脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆