【问题标题】:Not able to read json data in $_POST when sent using angularjs使用 angularjs 发送时无法读取 $_POST 中的 json 数据
【发布时间】:2014-03-23 08:17:26
【问题描述】:

我有角度:

var data = {};
data['name'] = "test";
data['class'] = "testClass";

$http.post('http://testURL',data,function(data){
console.log(data);
});

当我在 PHP 代码中:var_dump($_POST) 时,我得到一个空数组。因此我必须使用 file_get_contents("php://input");(原始数据流)访问数据。

问题:为什么我必须使用原始数据流?如果我在 jQuery 中使用普通的 ajax 调用发送数据,我可以在 $_POST 中获取数据,但在 angularjs 中这是不可能的?

【问题讨论】:

    标签: php jquery ajax json angularjs


    【解决方案1】:

    当您发布 json 数据时,内容类型将是 application/json。 PHP 中的 $_POST 数组仅在 post 数据为 www-form-urlencoded 时使用,而 application/json 则不是。这就是为什么你需要从 php://input 读取。

    但大多数流行的 php 框架在控制器上下文中使用更易读的 API 来处理这个问题:

    <?php
    class Controller {
        function action($request) {
            $data = $request->json();
        }
    }
    

    【讨论】:

      【解决方案2】:

      因为 AngularJS 默认以application/json 发送数据,这并没有错。 jQuery 在发送数据时将其转换为x-www-form-urlencoded

      如果您想以 jQuery 方式获取它,您可能需要在您的 http 提供程序上添加一些配置。

      我的应用上还有 jQuery 贡献,这是我的 http 配置:

      angular.module('app')
      .config(['$httpProvider', function($httpProvider){
          $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
          $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
          $httpProvider.defaults.transformRequest = function(data){ if (data) return jQuery.param(data); };
      
      }]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多