2017-02-28 34 views
0

我知道,你可以在導軌通過Ajax請求通過簡單地提供remote: true提交表單的特定表單字段:阿賈克斯軌道:遠程:真正對不提交

<%= form_for(@user, remote: true) do %> 
    ... 
<% end %> 

現在:當表單提交:而不是HTTP請求,它是一個Ajax請求。

我想要做的是提交一個JS請求(ajax請求)不適用於整個表格,但對於特定的字段元素,但它不起作用。具體做法是:

<%= form_for(@user) do %> 

    <div class="field"> 
    <%= f.label :food_type_id %> 
    <%= f.collection_select :food_type_id, FoodType.all, :id, :name, remote: true %>   
    </div> 

    ... 

<% end %> 

我希望一個AJAX請求,因爲我提供了關於該領域的remote: true選項被髮送到服務器:當用戶選擇框內選擇Ajax請求要火了。所以:每當用戶做出選擇時:ajax請求就會被觸發。但是:什麼都沒有發生。

我缺少什麼?我知道我可以自己做所有事情:將事件偵聽器綁定到客戶端的選擇框,並在選擇框更改時觸發請求。不過:我認爲remote: true可以爲你處理ajax請求,所以我不需要做任何自定義ajax請求的構建。

+0

當您嘗試提交的選擇是什麼JS控制檯說? – IvRRimUm

回答

2

Rails的內置形式助手允許您使用以下助手remote: trueform_tagform_forlink_tobutton_to。將remote: true添加到表單中的單個字段將不起作用。請參閱Working with Javascript in Rails

您需要綁定一個JavaScript函數的food_type_id選擇:

$('select#user_food_type_id').change(function() { 
    $.ajax({ 
    url: '/food_types.json', // you could be fancy and set this in a data attribute. 
    success: function(response) { 
     // update your form with the response from your ajax request 
    } 
    }); 
});