【问题标题】:CakePHP - POST call to REST API returning nullCakePHP - 对 REST API 的 POST 调用返回 null
【发布时间】:2012-03-02 16:05:19
【问题描述】:

我已经为我的 CakePHP 设置了 REST,但我遇到了一个小问题。当调用 GET 方法时,比如我的控制器上的视图或索引,甚至是 GET 的自定义方法,我都可以毫无问题地得到答案。但是,当我尝试执行诸如 add 之类的 POST 操作时,即使我可以看到它正确到达并执行(保存到数据库),我也没有从操作中得到任何输出。

我已经正确设置了 JSON 和 XML 输出的布局文件以及每种输出类型的路由和视图。

编辑:

beforeFilterAppController中的相关代码:

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

路线中的代码:

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

我在FonykersController 中的add 方法中的相关代码:

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

我在/views/fonykers/json的看法

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

我的 json 布局文件:

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

【问题讨论】:

  • 不看相关代码就无话可说。
  • 用相关代码更新了我的问题

标签: json cakephp rest cakephp-1.3


【解决方案1】:

你有一些事情正在发生......

您的 beforeFilter 检查 isAjax,然后使用 elseif 测试 XML 或 JSON。如果您的请求是 AJAX,它永远不会进入 XML/JSON 测试。您的布局可能根本没有设置,只剩下$this-&gt;autoRender = false;

由于禁用了自动渲染,在某些时候您必须手动调用渲染。使用$this-&gt;set() 只是准备在视图中使用的变量——它实际上并不输出视图。在您的控制器操作中,唯一实际输出任何内容的行是 echo json_encode($response);

使用$this-&gt;render() 强制Cake 在需要时渲染视图。更多信息The 1.3 Book: Rendering a specific view


顺便说一句,有时您使用...}elseif(...,有时您使用...}else if(...。这在技术上并没有错,但保持一致将使您的代码更易于阅读。

【讨论】:

  • 谢谢Farray,我会试一试告诉你。我之前检查过你所说的关于 autoRender 是假的,在这种情况下它没有发生,对我的 API 的调用是从 iOS 设备 atm 进行的,并且设置了正确的布局和渲染状态,它没有触及 AJAX 部分,因为这不是 AJAX 调用。所以看到它仍然没有解释为什么它没有渲染视图。
  • 好的,这个渲染成功了,看到我之前说的,还有其他原因导致它没有渲染吗?我的其他 API 调用呈现,它们的制作方式与此相同。
  • @8vius 抱歉,我误解了您问题的那一部分,并认为它不适用于 AJAX 方法。稍后会对此进行更多思考。
  • 诚实的错误,我很感激它,因为它导致了一个解决方案(即使它不是最合适的)。我暂时把这个问题留着。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2013-10-14
  • 2021-05-17
  • 2017-08-06
  • 2017-04-07
相关资源
最近更新 更多