duangou2028 2015-03-04 09:45
浏览 161
已采纳

angularjs - 将对象数组(JSON数据)POST到PHP页面

An example of how my JSON data is like:

$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:

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.

  • 写回答

3条回答 默认 最新

  • douwen5246 2015-03-04 10:32
    关注

    I've made plnkr for you 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

    <?php
      echo file_get_contents('php://input');
    

    I read the JSON directly and echo it but you can do whatever you want

    read more about php://input here 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?