2012-03-02 73 views
0

我已經爲我的CakePHP設置了REST,並且遇到了一些小問題。當調用一個GET方法時,比如我的控制器上的視圖或索引,甚至是一個GET方法的自定義方法,我都沒有問題得到答案。但是當我嘗試像添加一樣執行POST操作時,即使我可以看到它已正確到達並執行(保存到數據庫),也不會從操作中獲得輸出。CakePHP - POST調用REST API返回null

我已經正確設置了JSON和XML輸出的佈局文件以及每種輸出類型的路由和視圖。

編輯:beforeFilter

相關的代碼在AppController

 if ($this->RequestHandler->isAjax()) { 
     $this->layout = 'ajax'; 
     $this->autoRender = false; 
     } elseif ($this->RequestHandler->isXml()) { 
     $this->layout = 'default'; 
     $this->RequestHandler->respondAs('xml'); 
     $this->RequestHandler->renderAs($this, 'xml'); 
     } elseif ($this->RequestHandler->ext == 'json') { 
     $this->layout = 'default'; 
     $this->RequestHandler->respondAs('json'); 
     $this->RequestHandler->renderAs($this, 'json'); 
     } elseif ($this->RequestHandler->accepts('html')) { 
     $this->layout = 'frontend'; 
     } 

守則之路:我add方法

Router::mapResources('fonykers'); 
Router::mapResources('voicenotes'); 
Router::parseExtensions(); 

相關的代碼在FonykersController

$response = array('ok' => true, 'title' => 'Thank you for registering', 'msg' => 'A confirmation email has been sent to the provided email address, please click on the link in the email to complete the registration process'); 
if ($this->RequestHandler->isXml()) { 
    $this->set(compact('response')); 
} else if ($this->RequestHandler->ext == 'json') { 
    pr('This prints'); 
    $this->set(compact('response')); //View not being outputted 
    pr('This also prints'); 
} else { 
    echo json_encode($response); 
} 

我在JSON /views/fonykers/json

<?php echo json_encode(array('response' => $response)); ?> 

我的佈局文件視圖:

<?php 
header("Pragma: no-cache"); 
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate"); 
header('Content-Type: application/json'); 
header("X-JSON: ".$content_for_layout); 
echo $content_for_layout; 
?> 
+0

沒有看到相關的代碼就無法說出任何內容。 – JJJ 2012-03-02 17:01:33

+0

用相關代碼更新了我的問題 – 8vius 2012-03-02 17:19:36

回答

2

你有幾件事情怎麼回事...

你beforeFilter檢查isAjax,然後使用elseif測試XML或JSON。如果您的請求是AJAX,它將永遠不會進入XML/JSON測試。您的佈局很可能不會被設置,只會讓您僅使用$this->autoRender = false;

由於autoRender被禁用,在某些時候您必須手動調用渲染。使用$this->set()只准備在您的視圖中使用的變量 - 它並不實際輸出視圖。在您的控制器操作中,實際輸出任何內容的唯一行是echo json_encode($response);

使用$this->render()強制Cake在您需要時呈現視圖。在The 1.3 Book: Rendering a specific view


作爲一個更多信息之餘,有時你使用...}elseif(...,有時你使用...}else if(...。這在技術上不是錯誤的,但保持一致將使您的代碼更易於閱讀。

+0

謝謝Farray,我會試一試,讓你知道。我之前檢查過你說過autoRender是否爲false,並且在這種情況下不會發生這種情況,我的API的調用是由iOS設備atm製作的,並且設置了適當的佈局和呈現狀態,因爲它不會觸及AJAX部分,因爲這不是一個AJAX調用。所以看到它仍然沒有解釋爲什麼它不呈現視圖。 – 8vius 2012-03-02 18:03:51

+0

好吧,這個渲染工作,看到我之前說的是有沒有其他原因爲什麼它不呈現?我的其他API調用渲染,它們的製作方式與此相同。 – 8vius 2012-03-02 18:06:09

+0

@ 8vius對不起,我誤解了你的部分問題,並認爲它不適用於AJAX方法。稍後會再考慮一些。 – Farray 2012-03-02 18:31:13