2012-07-12 53 views
7

我試圖從使用JQuery網頁發送JSON數據,這樣的JSON數據:CakePHP的2.2檢索控制器

$.ajax({ 
    type: "post",  // Request method: post, get 
    url: "http://localhost/ajax/login", 
    data: '{username: "wiiNinja", password: "isAnub"}', 
    dataType: "json", // Expected response type 
    contentType: "application/json", 
    cache: false, 
    success: function(response, status) { 
     alert ("Success"); 
    }, 
    error: function(response, status) { 
     alert('Error! response=' + response + " status=" + status); 
    } 
}); 

在cake2.2,我有一個名爲Ajax控制器,有一個方法名爲「登錄」,這樣的:

public function login($id = null) 
{ 
    if ($this->RequestHandler->isAjax()) 
    { 
     $this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML 
     $this->autoLayout = false; 
     $this->autoRender = false; 

     $response = array('success' => false); 

     $data = $this->request->input(); // MY QUESTION IS WITH THIS LINE 
     debug($data, $showHTML = false, $showFrom = true); 
    } 
    return; 
} 

我只是想看看,如果我傳遞正確的數據給控制器。如果我用這條線:

$data = $this->request->input(); 

我可以看到調試打印輸出:

{username: "wiiNinja", password: "isCool"} 

我在CakePHP的手動2.X讀「訪問XML或JSON數據」下,它表明這個調用解碼數據:

$data = $this->request->input('json_decode'); 

當我調試打印$ data時,我得到「null」。我究竟做錯了什麼?我的數據是從Javascript傳入的嗎?或者我沒有正確調用解碼?

感謝您的任何建議。

=============我自己編輯========

通過實驗發現我自己的錯誤:

當通過JavaScript發佈代替,這條線:

data: '{username: "wiiNinja", password: "isAnub"}', 

將其更改爲:

data: '{"username": "wiiNinja", "password": "isAnub"}', 

在控制器代碼,改變這一行:

$data = $this->request->input('json_decode'); 

要:

$data = $this->request->input('json_decode', 'true'); 

它的工作原理。


Dunhamzzz,

當我跟着你的建議,並檢查在我的控制器代碼中的 「$這個 - >請求 - > PARAMS」 陣列,它包含以下內容:

array(
    'plugin' => null, 
    'controller' => 'ajax', 
    'action' => 'login', 
    'named' => array(), 
    'pass' => array(), 
    'isAjax' => true 
) 

正如你所看到的,我正在尋找的數據不在那裏。我已經得到了正確的路線代碼。這是什麼2.X的文件說,在這裏是一致的:

http://book.cakephp.org/2.0/en/controllers/request-response.html

到目前爲止,我發現使它工作的唯一辦法,是上面「我自己的編輯」說。但是,如果發送JSon字符串到服務器不是正確的事情,我想解決這個問題,因爲最終,我將不得不處理將發送JSon對象的第三方代碼。

回答

1

你正在爲數據掙扎的原因是你用jQuery發送一個字符串,而不是一個合適的JavaScript對象(JSON)。

$.ajax({ 
    type: "post",  // Request method: post, get 
    url: "http://localhost/ajax/login", 
    data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed 
    dataType: "json", // Expected response type 
    contentType: "application/json", 
    cache: false, 
    success: function(response, status) { 
     alert ("Success"); 
    }, 
    error: function(response, status) { 
     alert('Error! response=' + response + " status=" + status); 
    } 
}); 

現在,數據將以$this->request->params的PHP數組形式提供。

還用於發送JSON響應,please see this manual page。您的代碼大部分可以減少到只有2行...

//routes.php 
Router::parseExtensions('json'); 

//Controller that sends JSON 
$this->set('_serialize', array('data'));