由于我在我的cakephp项目中实施了授权,因此它无法使用JSON访问我的视图。我是否必须在任何地方设置特定设置才能再次进行此项工作? 我希望加入自动完成检查allowedActions和isAuthorized会做的伎俩在CakePHP中执行授权后,JSON视图不起作用
应用程序\控制器\ BrandsController.php(从不必要的代码剥离)
<?php
App::uses('Sanitize', 'Utility');
class BrandsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session', 'RequestHandler');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allowedActions = array('autoComplete');
}
public function isAuthorized($user) {
if ($this->action === 'view' || $this->action === 'index' || $this->action === 'autoComplete') {
return true;
}
return parent::isAuthorized($user);
}
public function autoComplete($name = null)
{
if(!$name)
{
$name = @$this->params->query['name'];
}
$name = Sanitize::paranoid($name, array(' '));
if (!$name || empty($name))
{
new NotFoundException(__('Invalid searchquery'));
}
else
{
$objects = $this->Brand->find('list',
array(
'conditions' => array("Brand.name LIKE" => "%" . $name . "%")
)
);
$this->layout = 'ajax';
$this->RequestHandler->setContent('json', 'application/json');
$this->set(compact('objects'));
$this->render('json/output_json');
}
}
}
?>
应用程序\查看\品牌\ JSON \ output_json.ctp
<?php
Configure::write('debug', 0);
echo json_encode($objects);
?>
呼叫
<?php
$brandsAutoCompleteUrl = Router::url(array('controller' => 'brands', 'action' => 'autoComplete'));
?>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('<?php echo $brandsAutoCompleteUrl; ?>', { name: 'test' }, function(data) {
// never called
});
});
</script>
在我的Chrome调试窗口,它最高审计机关
GET http://localhost/cakephp/brands/autoComplete?name=tes 500 (Internal Server Error)
当我直接调用这个网址从我的浏览器,我得到预期的结果
随着error500消息,您应检查的第一件事是你webserv的日志文件呃,它可能与auth组件没有关系。 – thaJeztah 2013-02-26 22:19:35
此外,与您的问题没有直接关系,但您需要更新CakePHP 2.3的代码。 '$ this-> params'仅用于向后兼容性,您应该使用请求对象; '$ this-> request-> query('name')'(请不要用'@'来压制错误)。 requestHandler也不是必需的,而是使用'response'对象。更多信息在这里; http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types,这里http://book.cakephp.org/2.0/zh/views/json-and -xml-意见。html – thaJeztah 2013-02-26 22:27:36
代码中的一些错误:您不会'抛出'您的异常,只是创建它(这可能会导致错误),并且您没有禁用autoRender,这可能会导致错误 – thaJeztah 2013-02-26 22:30:35