2015-05-14 44 views
4

我是AngularJS中的新成員,遵循一些教程,我可以創建一個簡單的頁面和一個簡單的表單。將數據發送到AngularJS的PHP腳本

問題是,我每次提交表單似乎都是腳本發送空數據。

這是我的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 

我錯過了什麼嗎?

+0

我已經更新了我的答案,包括下面的原因;希望這可以幫助。 – daxeh

+0

嘗試打印所有POST <?php print_r($ _ POST); ?>看看有什麼問題 –

+0

請顯示'processForm()'代碼# –

回答

4

你需要得到在PHP的數據,

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

$data->name // to access name 

OR

加入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, status, headers, 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'; 
}]) 
+2

而且,可以在AngularJS中更改內容類型。 – DWand

+0

確切:)..... –

+0

如果我添加'header'節沒有任何改變,同樣的問題。如果我添加'$ .param',我得到ReferenceError:$沒有定義 –

1

TL;DR Aha! since $scope.formData is an Object? Then do JSON.stringify() .

TL;DR Aha! since $errors is an array? Then do json_encode() .

JS:

$http.post('process.php', JSON.stringify($scope.formData)) ... 

PHP:

json_encode($errors); 

注:

write: JSON.stringify. json_encode() 
read: JSON.parse(), json_decode() 

至於AngularJS docs,它默認的頁眉設置(*注:dataType

設置HTTP頭

The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

$httpProvider.defaults.headers.common (headers that are common for all requests): 
Accept: application/json, text/plain, */* 
$httpProvider.defaults.headers.post: (header defaults for POST requests) 
Content-Type: application/json 
$httpProvider.defaults.headers.put (header defaults for PUT requests) 
Content-Type: application/json 

希望這有助於。

+0

問題是,在process.php $ _POST總是爲空 –

+0

@ChristianGiupponi,我更新了JSON的答案,stringify(對象),因爲$ scope.form是一個對象。看看這是怎麼回事。希望有所幫助。 – daxeh

相關問題