From UI I make call:
$http.post('services/loadCategory.php', {
'id' :'1',
'type' :'string'
}).then(function(response) {
debugger;
...
}, function(response) {
...
});
在PHP服务中,我无法从body POST请求中获取变量:
include ("bd.php");
header("Content-type: text/html; charset=windows-1251");
// ----- ----- ----- ----- -----
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
//
exit(json_encode(
array('type' => iconv('windows-1251', 'UTF-8', $_POST['type']),
'id' => iconv('windows-1251', 'UTF-8', $_POST['id'])
)));
请求服务:{id: ",类型:"}如何修复?
当向PHP发送JSON时,$_POST变量为空。要在PHP中获取原始JSON,请使用以下命令:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents('php://input'), true);
}
您可以使用$data['id']
和$data['type']
访问数据
用print_r($data);
检查传入的$数据
在对这个问题进行了快速搜索之后,似乎PHP很难对AngularJS发送的POST主体进行反序列化。AngularJS发送的所有信息都是JSON编码(application/json
),而大多数其他JavaScript变体发送的内容都是application/x-www-form-urlencoded
。
要解决这个问题,您应该将请求的内容类型设置为application/x-www-form-urlencoded
,或者您可以尝试下面来自类似问题的解决方案之一。
基于这个问题,下面的代码(由Felipe Miosso提供)似乎可以解决这个问题:
// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
或者,您可以通过向PHP添加以下代码行来解决此问题:
$params = json_decode(file_get_contents('php://input'),true);