2017-04-03 103 views
1

我在我的一個表單中設置了一個簡單的Ajax調用。當用戶在字段中輸入字符,下面的Ajax調用被激活:Symfony 3 Ajax呼叫路由問題

self.modify = function (input_field) { 
    if ($(input_field).val().length > 5) { 
     $.post("{{path('get_bio_control_sample')}}", {sample_number: $(input_field).val()}, 
      function (response) { 
       if (response.code == 100 && response.success) { 
        alert(response.sample_number); 
       } 
      }, "json"); 
    } 
}; 

這意味着訪問下面的控制器操作:

class BioControlController extends Controller { 
    /** 
    * @Route("/bio_control/sample", name="get_bio_control_sample") 
    */ 
    public function getBioControlSampleAction(Request $request){ 

     $sample_number = $request->query->get('sample_number'); 

     $response = array("code" => 100, "success" => true, "sample_number" => $sample_number, "sample_data" => "test"); 

     return new JsonResponse($response); 
    } 
} 

然而,當通話被激活JS返回錯誤:

http://127.0.0.1:8000/omics_experiment/%7B%7Bpath('get_bio_control_sample')%7D%7D 404 (Not Found) 

我訪問來自omics_experiment/new(這是在OmicsExperimentController)Ajax調用和使用路線/bio_control/sample(如由註釋顯示),但它不起作用。有人能解釋我做錯了什麼嗎?

我用this問題作爲模板,我使用Symfony 3的事實可能意味着有句法錯誤。

回答

1

我剛剛不得不這樣做最近。我也不是Symfony的專家,但是因爲我只是做了這個,所以我可能會提供幫助。使用Symfony與使用靜態URL進行操作並沒有多大區別。最重要的是確保你的控制器和路由設置正確並且在沒有AJAX的情況下工作,那麼你只需要使用路由中爲.post調用設置的路徑。

更糟糕的是,測試這種類型的交互真的很難。即使你的小枝包含它也會導致它失敗,如果它們設置錯誤的話。

再次查看您的代碼我認爲這可能是問題所在。改變這種

$.post("{{path('get_bio_control_sample')}}", {sample_number: 

這個

$.post("/bio_control/sample", {sample_number: 

因爲我覺得你的方式僅適用於枝模板好,所以如果Symfony的不看你的JQuery的文件中像它做了樹枝模板,那麼,它就不會理解如何獲得路線。

+1

謝謝,這工作完美! – Darkstarone

+0

太棒了!很高興我能幫上忙! – garek007