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); };
}]);