2012-03-02 68 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