Symfony2,检查一个动作是否被 ajax 调用 [英] Symfony2, check if an action is called by ajax or not

查看:30
本文介绍了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 YOURBundleNamespace

use SymfonyComponentHttpFoundationRequest;

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆