Angular JS:为什么我无法通过`$ http`发送数据?

时间:2014-05-20 10:13:48

标签: javascript web-services angularjs http

在我的控制器中,我通过以下方式发送http请求:

var postData = { action: 'getTasksByProjectSlug', slug: 'inbox' }

$http({
    url: 'http://localhost/toodloo/api/kernel.php',
    method: 'POST',
    data: postData,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function( data, status, headers, config ){
    console.log( data );
}).error(function( data, status, headers, config ) {
    console.log( status );
});

并且在kernel.php我有以下内容:

class Kernel
{
    function __construct( $requestData )
    {
        if ( ( isset( $requestData ) === false ) || empty( $requestData ) ) {
            die( 'No data received!' );
        }

        $this->findRoute( $requestData );
    }

    public function findRoute( $requestData ) {
        ...
        } else if ( ( $requestData['action'] === 'getTasksByProjectSlug' ) && isset( $requestData['slug'] ) ) {
            $this->getTasksByProjectSlug( $requestData['slug'] );
        } else {
        ...
    }

    public function getTasksByProjectSlug( $slug ) {
        $project = new Project;
        $tasks = $project->getTasksByProjectSlug( $slug );

        $json = json_encode( $tasks );
        echo $json;

        return $json;
    }
}

$kernel = new Kernel( $_POST );

现在问题是console.log( data ); success $http'No data received'返回的所有问题都是( isset( $_POST ) === false ) || empty( $_POST ) ),这就是API在var postData = { action: 'getTasksByProjectSlug', slug: 'inbox' }条件下的作用因此我从中推断出请求被发送到服务器,但是我发送的数据postData在某种程度上没有在服务器端收到。

有谁能告诉我这里可能做错了什么?为什么data: JSON.stringify(postData)没有在服务器端发送?

P.S:我也试过{{1}}但结果仍然相同

1 个答案:

答案 0 :(得分:0)

Kernel类实例化的顶部添加以下内容,对我有用:

$requestParams = json_decode(file_get_contents('php://input'));
$requestParams = (array) $requestParams;

现在$requestParams的行为就像$_POST