Symfony2,检查动作是否被ajax调用 [英] Symfony2, check if an action is called by ajax or not
本文介绍了Symfony2,检查动作是否被ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于控制器中的每个动作,我都需要检查这些动作是否由ajax请求调用.
I need, for each action in my controller, check if these actions are called by an ajax request or not.
如果是,则不添加任何内容,如果否,则需要重定向到主页.
If yes, nothing append, if no, i need to redirect to the home page.
我刚刚找到了 if($ this-> getRequest()-> isXmlHttpRequest())
,但是我需要在每个操作上添加此验证..
I have just find if($this->getRequest()->isXmlHttpRequest())
, but i need to add this verification on each action..
您知道更好的方法吗?
推荐答案
非常简单!
只需在您的方法中添加$ request变量即可使用.(对于每个控制器)
Just add $request variable to your method as use. (For each controller)
<?php
namespace YOUR\Bundle\Namespace
use Symfony\Component\HttpFoundation\Request;
class SliderController extends Controller
{
public function someAction(Request $request)
{
if($request->isXmlHttpRequest()) {
// Do something...
} else {
return $this->redirect($this->generateUrl('your_route'));
}
}
}
如果要自动执行此操作,则必须定义一个内核请求侦听器.
If you want to do that automatically, you have to define a kernel request listener.
这篇关于Symfony2,检查动作是否被ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文