Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用angularjs发送时无法读取$\u POST中的json数据_Php_Jquery_Ajax_Json_Angularjs - Fatal编程技术网

Php 使用angularjs发送时无法读取$\u POST中的json数据

Php 使用angularjs发送时无法读取$\u POST中的json数据,php,jquery,ajax,json,angularjs,Php,Jquery,Ajax,Json,Angularjs,在这方面,我有: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); 当在PHP代码中执行以下操作时:var\u dump($\u POST),我得到一个空数组。因此,我必须使用file\u get\u contents(“php://input");(原始数据流) 问

在这方面,我有:

var data = {};
data['name'] = "test";
data['class'] = "testClass";

$http.post('http://testURL',data,function(data){
console.log(data);
});
当在PHP代码中执行以下操作时:
var\u dump($\u POST)
,我得到一个空数组。因此,我必须使用
file\u get\u contents(“php://input");(原始数据流)


问题:为什么我必须使用原始数据流?如果我在jQuery中使用普通的ajax调用发送数据,我可以在$\u POST中获取数据,但在angularjs中这是不可能的?

当您发布json数据时,内容类型将按应用程序/json显示。PHP中的$\u POST数组仅在POST数据为www form urlencoded时使用,而application/json不是。这就是为什么你需要阅读的原因php://input.

但大多数流行的php框架在控制器上下文中使用更具可读性的API来处理此问题:

<?php
class Controller {
    function action($request) {
        $data = $request->json();
    }
}

因为AngularJS在默认情况下以
application/json
的形式发送数据,这没有什么错。jQuery在发送数据时将其转换为
x-www-form-urlencoded

如果您想以jQuery方式获得它,您可能需要在
http
提供程序上添加一些配置

我的应用程序上仍然有jQuery贡献,这是我的
http
config:

angular.module('app')
.config(['$httpProvider', function($httpProvider){
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    $httpProvider.defaults.transformRequest = function(data){ if (data) return jQuery.param(data); };

}]);