下面的$http request
成功执行,但是另一端的PHP脚本在接收'test‘和’testval‘时接收空的$_POST
数组。有什么想法吗?
$http({
url: 'backend.php',
method: "POST",
data: {'test': 'testval'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {});
发布于 2014-01-06 13:32:44
如果您只想发送这些简单的数据,请尝试如下:
$http({
url: 'backend.php',
method: "POST",
data: 'test=' + testval,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {});
而php部分应该是这样的:
<?php
$data = $_POST['test'];
$echo $data;
?>
对我来说很管用。
发布于 2013-11-20 17:33:30
这是AngularJS的一个常见问题。
第一步是更改POST请求的默认内容类型标头:
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded; charset=UTF-8;";
然后,使用XHR请求拦截器,有必要正确序列化有效负载对象:
$httpProvider.interceptors.push(['$q', function($q) {
return {
request: function(config) {
if (config.data && typeof config.data === 'object') {
// Check https://gist.github.com/brunoscopelliti/7492579
// for a possible way to implement the serialize function.
config.data = serialize(config.data);
}
return config || $q.when(config);
}
};
}]);
这样,有效负载数据将再次在$_POST数组中可用。
有关XHR interceptor的更多信息。
另一种可能是对默认的内容类型标头进行处理,然后服务器端解析有效负载:
if(stripos($_SERVER["CONTENT_TYPE"], "application/json") === 0) {
$_POST = json_decode(file_get_contents("php://input"), true);
}
发布于 2014-07-17 13:23:01
更简化的方式:
myApp.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined) { return data; }
return $.param(data);
};
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
https://stackoverflow.com/questions/19213903
复制相似问题