在CakePHP中,框架使用扩展名.json
URL或搜索Accepts
http标头来检测要返回的数据类型。
在 JSONP 中,我无法修改 hTTP 标头。 https://stackoverflow.com/a/19604865/80353
我想避免使用 .json
然后,我尝试使用以下代码设置 viewClass:
if ($this->request->is('ajax')) {
$this->log('enter here');
$this->viewClass = 'Json';
}
随后,我意识到该请求将不起作用,因为标头不包含XMLHTTPRequest。
我的问题是:
1) 如何在不求助于 URL 中的扩展名的情况下返回 jsonp 请求的 Json 数据?
2)Cakephp有没有办法检测JSONP请求?我的直觉说这是不可能的。
我需要一个 jsonp 来处理 openlayer 的边界框功能,我做了这样的事情:
在控制器功能中:
$this->layout = false;
// get the callback from the request
$callback = $this->request->query['callback'];
$data = // do something usefull...
$this->set('callback', $callback);
$this->set('json', $data);
$this->render('../Elements/jsonp');
和元素:
<?php
$tmp = json_encode($json);
/* Generic JSON template */
if(!isset($debug)){
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
//header('Content-Type: application/json');
}
echo $callback . '({ "type": "FeatureCollection",
"features": ' . $tmp . '});';
;
?>
如您所见,我做了一些懒惰的编程来"构建"元素中的输出格式。对于其他形式的数据,这很容易被修改。
编辑:
不需要使用扩展,因为您在控制器中调用函数。
使用配置/路由中的选项.phphttp://book.cakephp.org/2.0/en/development/routing.html#file-extensions
Router::parseExtensions('xml', 'json');
控制器中的函数名称将为:
json_myfunction(){ ...
URL 将变为:
localhost/json/mycontroller/myfunction?param1=...
JSONP请求将包含一个指定javascript回调函数名称的查询字符串var(通常名为callback
)。因此,您可以检查一下:
if ($this->request->query('callback')) { /*do stuff*/ }