angularjs - 将对象数组(JSON 数据)发布到 PHP 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28851154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angularjs - POST an array of objects(JSON data) to a PHP page
提问by Keval
An example of how my JSON data is like:
我的 JSON 数据示例如下:
$scope.a = [{
"email": "keval@gmail",
"permissions": {
"upload": "1",
"edit": "1"
}
}, {
"email": "new@aa",
"permissions": {
"upload": "1",
"edit": "1"
}
}];
I want to post the same, and here's my approach:
我想发布相同的内容,这是我的方法:
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: {
mydata: $scope.a
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});
And the PHP is to take the request and respond:
而 PHP 则是接受请求并做出响应:
echo $_POST['mydata'];
I tried JSON.stringify
before the call and json_decode
while echoing it back; still didn't work. Been trying all the possibilities I can think of, and what I find on the web/other questions, but still not working.
我JSON.stringify
在通话前和json_decode
回声时尝试过;仍然没有工作。一直在尝试我能想到的所有可能性,以及我在网络/其他问题上找到的内容,但仍然无法正常工作。
回答by maurycy
I've made plnkr for you http://plnkr.co/edit/K8SFzQKfWLffa6Z4lseE?p=preview
我已经为你制作了 plnkr http://plnkr.co/edit/K8SFzQKfWLffa6Z4lseE?p=preview
$scope.postData = function () {
$http.post('http://edeen.pl/stdin.php', {user:$scope.formData}).success(
function(data){
$scope.response = data
})
}
as you can see I'm sending a raw JSON without formating it, then in php
正如你所看到的,我发送了一个未格式化的原始 JSON,然后在 php 中
<?php
echo file_get_contents('php://input');
I read the JSON directly and echo it but you can do whatever you want
我直接读取 JSON 并回显它,但你可以做任何你想做的事
read more about php://input
here http://php.net/manual/en/wrappers.php.php
阅读更多关于php://input
这里http://php.net/manual/en/wrappers.php.php
I was using it for a long time for REST services to avoid transforming JSON to string to many times
我在 REST 服务中使用了很长时间,以避免多次将 JSON 转换为字符串
回答by Antonio Reyes Montufar
I use this, with which I can send Array JSON:
我使用它,我可以用它发送数组 JSON:
var array = {}
array['key1'] = value1;
array['key2'] = value2;
$http.post(URL, array)
.success(function(data){
})
.error(function(){
});
回答by Ben Hsieh
try using $httpParamSerializer or $httpParamSerializerJQLike
尝试使用 $httpParamSerializer 或 $httpParamSerializerJQLike
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: $httpParamSerializer($scope.a),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});