2012-07-12 4 views
7

나는이 같은 jQuery를 사용하여 웹 페이지에서 JSON 데이터를 전송하기 위해 노력하고있어에서 JSON 데이터를 검색 2.2 CakePHP의 :컨트롤러

$.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, 나는 방법을 가지고 아약스라는 이름의 컨트롤러가

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; 
} 

올바른 데이터를 컨트롤러에 전달하고 싶은지 확인하고 싶습니다. 나는이 회선을 사용하는 경우 :이 호출을 제안, "액세스 XML 또는 JSON 데이터"에서 내가 CakePHP의 수동 2.x를 읽어

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

:

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

나는 디버그 출력을 볼 수 있습니다 데이터를 디코딩하려면 :

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

출력 $ 데이터를 디버깅 할 때 "null"이 표시됩니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 내 데이터가 Javascript에서 잘못 전달 되었습니까? 아니면 디코딩을 올바르게 호출하지 않습니까?

의견을 보내 주셔서 감사합니다.

내 자신의 편집 ========

는 실험을 통해 내 자신의 실수를 찾을 수 ============= :

대신, 자바 스크립트를 통해 게시 이 라인 :

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

님의

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

변경을

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

사람 : : 그것은 작동

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

컨트롤러 코드에서

이 줄을 변경.

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

:


Dunhamzzz이

나는 당신의 제안을 따라하고 내 컨트롤러 코드에서 "$ this-> 요청 -> PARAMS"배열을 검사 할 때 다음 포함 보시다시피, 내가 찾고있는 데이터가 없습니다. 이미 적절한 경로 코드를 얻었습니다. 이 2.X에 대한 설명서는 여기 말씀과 일치 :

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

지금까지, 나는 그것이 작동하도록있는 유일한 방법은, "내 자신의 편집 '에 위에 언급 한 바와 같이합니다. 그러나 JSon 문자열을 서버에 보내는 것이 올바른 일이 아니라면 JSon 객체를 보낼 제 3 자 코드를 처리해야하므로이 문제를 해결하고 싶습니다.

답변

1

당신이 올바른 자바 스크립트 개체 (JSON)가 아닌 jQuery를 사용하여 문자열을 보내고 있기 때문에 데이터가 고질적 인 이유가 있습니다.

$.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')); 
관련 문제