Symfony2|为什么控制器操作执行两次


Symfony2 | Why controller action executes twice?

几天来,我一直面临着与Symfony的怪异行为。我有一个操作,由于某种原因,我需要在会话中存储一个随机值作为表单nonce。nonce被传递给一个ajax函数要使用的twitch模板。

在向相应动作发送随机数时,检查差异随机数值,因此请求被拒绝。

测试表明,该操作由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")

几天前我遇到了类似的问题,正如Richard所说,这个问题可以在我的应用程序的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
            }
        });
    });
}