haw*_*ris 14 javascript php angularjs
以下$http request执行成功,但另一端的PHP脚本在$_POST收到'test'和'testval'时会收到一个空数组.有任何想法吗?
$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) {});
Run Code Online (Sandbox Code Playgroud)
小智 18
如果您想发送这些简单数据,请尝试以下方法:
$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) {});
Run Code Online (Sandbox Code Playgroud)
而php部分应该是这样的:
<?php
$data = $_POST['test'];
$echo $data;
?>
Run Code Online (Sandbox Code Playgroud)
它对我有用.
这是AngularJS的常见问题.
第一步是更改POST请求的默认内容类型标头:
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded; charset=UTF-8;";
Run Code Online (Sandbox Code Playgroud)
然后,使用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);
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
这样,有效载荷数据将在$ _POST数组中再次可用.
有关XHR拦截器的更多信息.
另一种可能性是,它保留默认的内容类型头,然后服务器端解析有效负载:
if(stripos($_SERVER["CONTENT_TYPE"], "application/json") === 0) {
$_POST = json_decode(file_get_contents("php://input"), true);
}
Run Code Online (Sandbox Code Playgroud)
更简化的方式:
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';
});
Run Code Online (Sandbox Code Playgroud)