簡體   English   中英

如果請求的內容類型為application / json,cakephp如何將有效負載放入$ this-> request-> data?

[英]if request has content-type as application/json, how does cakephp fit the payload into $this->request->data?

我注意到我的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請求。

我的問題是Content-Typeangularjs默認標頭是application/json;charset=utf-8 ,如果我將其用作默認標頭並使用JSON.stringify我的數據,

CakePHP可以使用它嗎?

如果沒有,我需要在CakePHP上下文中對我的代碼進行哪些更改?

讀到告訴我們:

如果您的Content-Type是通常的application/x-www-form-urlencoded ,那么即使您發送了ajax請求, CakePHP也會幫助您將有效負載正確解析為$this->request->data

但是,如果Content-Typeapplication/json ,則需要使用$this->request->input('json_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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM