簡體   English   中英

Symfony2 | 為什么控制器動作執行兩次?

[英]Symfony2 | Why controller action executes twice?

幾天來,我面對着Symfony的奇怪行為。 我有一個動作,由於某種原因,我需要在會話中將隨機值存儲為隨機數形式。 隨機數被傳遞到樹枝模板以供ajax函數使用。

在將隨機數發送到相應操作時,將檢查差異隨機數值,因此請求被拒絕。

測試表明,該操作由Symfony執行了兩次,因此將在不更新前端的情況下存儲新的隨機數。 我無法確定原因。

經過數百次測試,我發現路線上的微小變化可以解決問題,但我不相信這是最終的解決方案,而且我找不到根本原因。

有人可以幫忙嗎?

這是有問題的代碼:

/**
 * 
 * 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")

幾天前我遇到了類似的問題,正如理查德所說,該問題將在我的應用程序的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();
    //...
});

為了解決我的問題,我必須添加$( "body" ).off( "submit", "**" ); 在我的函數initializeForm中,以清除附加到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
            }
        });
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM