2016-04-01 27 views
1

我不能讓下面的代碼工作!

<input type="text" ng-model="name" > 
<button ng-click="send(name);">SEND</button> 

angular.module('myapp', []). 
controller('MyController', ['$scope','$http', function ($scope,$http) { 
    $scope.name='Jim'; 
    $scope.send=function() { 
     return $http({ 
      method: 'POST', 
      data:{server:'Hi'}, 
      url: 'test.php', 
      dataType: 'json' 
     }).then(function(data){console.log(data)},function(data){console.log('failure')}); 
}; 
}]); 

和我的很簡單test.php

<?php 
$request=$_POST['server']; 
$request.='Jim'; 
echo json_encode($request); 
?> 

按下按鈕來發送,我收到($ HTTP成功返回):Object {data: ""Jim"", status: 200, config: Object, statusText: "OK"}。爲什麼數據等於該對象以及爲什麼'Hi'未傳遞給PHP? 請有人幫忙。我會瘋了!

回答

3

可能是因爲你的PHP腳本,你在錯誤的方式讀取請求的主體,嘗試:

<?php 
header("Content-Type: application/json"); 
$entityBody = file_get_contents('php://input'); 
$request = json_decode($entityBody); 
$request->server .= ' Jim'; 
echo json_encode($request); 
?> 
1

我只是碰到了這個問題,前幾天。 Angular $ http不會像PHP所期望的那樣序列化POST數據,而且我也不認爲Content-Type設置正確。如果您希望php獲取請求變量$ POST,並且不需要從'php:// input'讀取數據,則需要序列化您的發佈數據並確保Content-Type是正確的。這對我來說很有用。

$http({ 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' 
     }, 
    data: formatPostData({server:'Hi'}), 
    url: 'test.php', 
    dataType: 'json' 
}) 

而用於序列化發佈數據的功能就是這樣。

function formatPostData(args) { 
    var postString = ''; 
    angular.forEach(args, function(v, k){ 
     postString += k + '='+encodeURIComponent(v)+'&'; 
    }) 
    return postString.slice(0, -1); 
}