2014-01-20 24 views
2

我是cakePHP的新手。不用說我不知道​​從哪裏開始閱讀。閱讀幾個關於AJAX和JSON響應的網頁,我能夠理解的是,我需要使用Router::parseExtensions()RequestHandlerComponent,但沒有一個可以讀取示例代碼。使用CakePHP進行簡單的AJAX/JSON響應

我需要的是調用函數MyController::listAll()並返回Model::find('all')JSON格式,所以我可以使用它與JS。

這個我需要View嗎? 該視圖應該放在哪個文件夾中? 它應該有什麼樣的擴展? 我在哪裏可以放Router::parseExtension()RequestHandlerComponent

// Controller 
public function listAll() { 
    $myModel = $this->MyModel->find('all'); 

    if($this->request->is('ajax') { 
     $this->layout=null; 

     // What else? 

    } 
} 
+0

你不需要一個視圖模板,你可以簡單地使用JsonView爲[記錄](http://book.cakephp.org/2.0/en/views/json-and-xml-views.html ) – mark

回答

4

我不知道你讀了什麼,但我想這不是the official documentation。官方文檔包含如何做到這一點的例子。

class PostsController extends AppController { 
    public $components = array('RequestHandler'); 

    public function index() { 
     // some code that created $posts and $comments 
     $this->set(compact('posts', 'comments')); 
     $this->set('_serialize', array('posts', 'comments')); 
    } 
} 

如果動作被稱爲與以.json擴展你的JSON回來,如果它與.XML你會得到XML回叫。

如果你想或需要你仍然可以創建視圖文件。 Its as well explained on that page

// Controller code 
class PostsController extends AppController { 
    public function index() { 
     $this->set(compact('posts', 'comments')); 
    } 
} 

// View code - app/View/Posts/json/index.ctp 
foreach ($posts as &$post) { 
    unset($post['Post']['generated_html']); 
} 
echo json_encode(compact('posts', 'comments')); 
+0

好的,但那麼如何使用你已經序列化的這個響應?它變成了xmlhttp.responseText?我的問題:http://stackoverflow.com/questions/27979813/how-to-use-response-from-any-xmlhttprequest-in-cakephp-2-5請! –

1
// Controller 
public function listAll() { 
    $myModel = $this->MyModel->find('all'); 

    if($this->request->is('ajax') { 
     $this->layout=null; 
     // What else? 
     echo json_encode($myModel); 
     exit; 
     // What else? 

    } 
} 

必須回聲使用後退出,你已經使用了佈局空,因此這是確定的。

您不必爲此使用View,並且您希望使用組件。那麼你可以從控制器本身做到,而且沒有任何問題!

Iinjoy

+0

我發現這比Cake的內置方法更直接,但是在動作中退出可能會阻止任何過濾器或關閉方法。除了「退出」,您可以添加以下內容:「$ this-> layout = false」和「$ this-> render(false)」以獲得相同效果,而不會過早結束腳本。 – Synexis

+0

我的問題:http://stackoverflow.com/questions/27979813/how-to-use-response-from-any-xmlhttprequest-in-cakephp-2-5請! –