【问题标题】:Get masterRequest URL in a fragment controller在片段控制器中获取 masterRequest URL
【发布时间】:2016-08-02 09:07:08
【问题描述】:

我已经创建了一个在单击按钮时由 Ajax 请求调用的方法。

/**
 * @param Request $request
 *
 * @Route("/add", name="rapid_access_add", options={"expose"=true})
 * @Method({"GET"})
 *
 * @return Response
 */
public function addRouteAction(Request $request)
{
    $title = $request->query->get('title');
    $user = $this->getUser();

    $url = $this->get('request_stack')->getMasterRequest()->getUri();

    $rapidAccess = new RapidAccess();
    $rapidAccess->setUrl($url)
        ->setTitle($title)
        ->setUser($user);

    $em = $this->getDoctrine()->getManager();
    $em->persist($rapidAccess);
    $em->flush();

    $this->addFlash('success', $this->get('translator')->trans('user.flash.rapid_access_added', ['%title%' => $title], 'front'));

    return new Response('OK');
}

我正在尝试获取当前页面的 URL,由另一个控制器呈现(此方法在片段控制器中)。

但是当我使用 $this->get('request_stack')->getMasterRequest()->getUri(); 时,这给了我 addRouteAction 方法的 URL。

这应该给我主请求 URL,但我不明白为什么这会给我这个方法 URL。如何获取当前页面 URL 而不是此方法 URL?

也许我应该用 JS 获取 URL?

谢谢

【问题讨论】:

    标签: php ajax symfony


    【解决方案1】:

    为什么要使用请求栈?

    您可以直接使用控制器中的Request

    $request->getUri();
    

    【讨论】:

    • Request 也给了我addRouteAction URI。所以我尝试了请求堆栈
    • 你试过$request->getRequestUri();$request->getBasePath()吗?
    • 是的,$request->getRequestUri(); 给了我相同的 URL,$request->getBasePath(); 为空
    • 好的,那你为什么不恢复你之前想要的 URL(在 ajax 调用中)然后你把它发送到 addRouteAction 来得到它:$request->query->get('my_master_url')
    • 是的,我就是这样做的。这运作良好。谢谢你!
    猜你喜欢
    • 2017-12-16
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2012-03-05
    相关资源
    最近更新 更多