2016-04-01 24 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); 
}