由于我在我的 cakephp 项目中实现了授权,因此我无法再使用 JSON 访问我的视图。我是否必须在任何地方设置特定设置才能使其再次工作?我希望将 autoComplete 添加到 allowedActions 和 isAuthorized 可以解决问题
app\Controller\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)
当我直接从浏览器调用这个 url 时,我得到了预期的结果