如果请求的内容类型为application/json,那么cakephp如何将负载放入$this->;请求->;数据?

如果请求的内容类型为application/json,那么cakephp如何将负载放入$this->;请求->;数据?,json,angularjs,cakephp,payload,Json,Angularjs,Cakephp,Payload,我注意到我的angularjs需要如下设置标题,以便它能够与CakePHP很好地协同工作 angularApp.config(function ($httpProvider) { $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLH

我注意到我的
angularjs
需要如下设置标题,以便它能够与
CakePHP
很好地协同工作

angularApp.config(function ($httpProvider) {
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  $httpProvider.defaults.headers.common['Accept'] = 'application/json';
  $httpProvider.defaults.transformRequest = function(data) {
      if (data === undefined) {
          return data;
      }
      return $.param(data);
  }
});
我的
CakePHP
是2.4版本,使用
JsonView
呈现ajax请求

我的问题是
angularjs
内容类型的默认头是
application/json;charset=utf-8
如果我使用它作为默认值,并使用JSON.stringify我的数据

CakePHP
可以使用它吗

如果没有,我需要在
CakePHP
上下文中对代码进行哪些更改?

阅读告诉我们:

如果您的
内容类型
是通常的
应用程序/x-www-form-urlencoded
,那么即使您发送
ajax
请求,
CakePHP
也将帮助您正确地将有效负载解析为
$this->request->data

但是,如果
内容类型
应用程序/json
,则需要使用
$this->request->input('json\u decode')

基本上,我们假设您的angularjs配置为:

angularApp.config(function ($httpProvider) {
  // because you did not explicitly state the Content-Type for POST, the default is application/json
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  $httpProvider.defaults.headers.common['Accept'] = 'application/json';
  $httpProvider.defaults.transformRequest = function(data) {
      if (data === undefined) {
          return data;
      }
      //return $.param(data);
      return JSON.stringify(data);
  }
});
那里有不完整的信息

假设您仍在接收数据并将其作为一个数组进行操作,您需要实际使用
$this->request->input('json_decode',true)

要帮助解决问题,请将其另存为AppController上或相应控制器上的受保护方法

protected function _decipher_data() {
    $contentType = $this->request->header('Content-Type');
    $sendsJson = (strpos($contentType, 'json') !== false);
    $sendsUrlEncodedForm = (strpos($contentType, 'x-www-form-urlencoded') !== false);

    if ($sendsJson) {
        $this->request->useful_data = $this->request->input('json_decode', true);
    }
    if ($sendsUrlEncodedForm) {
        $this->request->useful_data = $this->request->data;
    }
    return $this->request->useful_data;
}
然后在适当的行动中,你可以

$data = $this->_decipher_data();
$data['User']['id'] = $id;

在beforeFilter中,您可以执行以下操作:

$this->_decipher_data();
$this->request->useful_data['User']['id'] = $id
然后在适当的操作中,执行以下操作:

$this->_decipher_data();
$this->request->useful_data['User']['id'] = $id