【问题标题】:Symfony2 | Why controller action executes twice?Symfony2 |为什么控制器动作执行两次?
【发布时间】:2016-05-15 20:50:31
【问题描述】:

几天来,我在 Symfony 中遇到了一种奇怪的行为。 我有一个动作,出于某种原因,我需要在会话中将随机值存储为 nonce 形式。 nonce 被传递给 twig 模板以供 ajax 函数使用。

在将 nonce 发送到相应的操作时,会检查差异 nonce 值,因此请求被拒绝。

测试表明,Symfony 执行了两次操作,因此将存储一个新的 nonce,而无需更新前端。我无法确定原因。

经过数百次测试,我发现路线的微小变化可以解决问题,但我不相信这是最终的解决方案,我找不到根本原因。

有人可以帮忙吗?

这是有问题的代码:

/**
 * 
 * Condo Apartments management 
 * 
 * @Route("/condo/apartment")
 */
class ApartmentController extends Controller
{
    /**
     * Index Condo Apartments
     * 
     * @Route("/edit/{id}/{apartment}", name="edit_apartment")
     * @Route("/manage/{id}", name="manage_apartments")
     * @ParamConverter("apartment", class="RimakishCondominiumBundle:Apartment", options={"mapping":{"apartment"="id"}})
     * @Method({"GET", "POST"})
     */
    public function indexApartmentsAction( Request $request, Complex $complex, Apartment $apartment=null){


    $session = $request->getSession();
    $nonce = sha1(uniqid());
    if($session->has('nonce')){
        $session->remove('nonce');
    }

    $session->set('nonce', $nonce);

我刚刚将第一条路线更改如下,它起作用了。现在我需要知道这个问题的根本原因。

* @Route("/{id}/{apartment}/edit", name="edit_apartment")

【问题讨论】:

  • 我正在使用 Symfony 2.8
  • 最简单的原因通常是正确的答案。似乎您的 ajax 函数调用了 URL 两次。您应该调试完整的请求 - 如果通过 ajax 多次调用此方法应该非常明显。
  • 谢谢理查德,但那是我测试的一部分。我对服务器-客户端通信进行了严格监控,以确保没有从浏览器发送到服务器的额外查询。我还检查了服务器端相同的 Doctrine 查询数量。请记住,ajax 调用了另一个动作,我修改了路由来解决问题。如果 ajax 有问题,更改路由也无济于事。

标签: php symfony doctrine-orm


【解决方案1】:

几天前我也遇到了类似的问题,正如理查德所说,问题是在我的应用程序的 js 部分找到的。 就我而言,我使用 on() jquery 方法是因为我的页面中的动态内容,并且事件处理程序在某些特定情况下“累积”。 我不得不使用 off() 方法,这解决了我的多个 ajax 调用。

我的代码如下所示:

// A function executed when clicking a button with class ".modal-form"
$('body').on('click', '.modal-form', function (e) {
    //...(loading a form in a modal)
    //calling a function that initializes my form
    initializeForm();
    //...
});

为了解决我的问题,我必须在我的函数 initializeForm 中添加 $( "body" ).off( "submit", "**" ); 以清除所有附加到 id 为“my-form”的元素的事件处理程序

function initializeForm(){
    $( "body" ).off( "submit", "**" ); // I had to add this to avoid sending multiple ajax
                                       //requests in case the button with ".modal-form"
                                       //class has been clicked several times
    $('body').on('submit', '#my-form', function(e) {
        //...
        $.ajax({
            // That request was being sent several times
            }
        });
    });
}

【讨论】:

  • 谢谢鲁比,请查看我对理查德评论的评论
猜你喜欢
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 2016-10-07
  • 1970-01-01
相关资源
最近更新 更多