2010-11-29 118 views
1
獲取數據

我有以下型號:Ruby on Rails的 - jQuery的使用AJAX

create_table "mouldings", :force => true do |t| 
    t.string "suppliers_code" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "name" 
    t.integer "supplier_id" 
    t.decimal "length",   :precision => 3, :scale => 2 
    t.decimal "cost",   :precision => 4, :scale => 2 
    t.integer "width" 
    t.integer "depth" 
end 

當用戶在窗體上選擇造型我想通過Ajax獲得的成型的成本,並用它來得到一個使用JavaScript生成報價。下面是從表單中選擇標籤:

<select id="order_item_moulding_1_id" name="order_item_moulding_1[id]"> 
    <option value="">Select a moulding 1</option> 
    <option value="1">123 589 698</option> 
    <option value="2">897 896 887</option> 
    <option value="3">876 234 567</option> 
</select> 

這裏是JavaScript文件的一部分:

$(document).ready(function() { 

    $('#order_item_moulding_1_id').change(function() { 
    var moulding_1_price = ; 
    }); 

}); 

如何使用Ajax來設置變量moulding_1_price?

回答

3

如果你想要通過ajax在您的導軌控制器中執行此操作,您只需將每個選項的值設置爲您正在查找的成型件的ID,然後使用jQuery的ajax方法將其發送到您的控制器:

var theVal = $('#order_item_moulding_1_id').val(); 
var theURL = '/someUniqueRoutingKeywordSuchAsMouldingAjax/' + theVal; 


     $.ajax({ 
      url: theURL 

     }); 

然後確保你在你的routes.rb文件中的路由集:

match 'someUniqueRoutingKeywordSuchAsMouldingAjax/:id', :to => 'yourMouldingsController#ajaxMouldings' 

而在你yourMouldingsController,自定義一個方法:

def ajaxMouldings 
@moulding = Moulding.find(params[:id]) 

end 

默認情況下,這會使ajaxMouldings.js.erb。所以在你的觀點中,確保你有一個名字的文件。這是嵌入的JavaScript,所以你可以用它來代替你的頁面上的一些DIV要顯示的信息:

// in ajaxMouldings.js.erb 
// be sure to escape any dynamic values! 
alert('Hey, it worked!'); 

var theHTML = '<div class="moulding_title"><%= escape_javascript(@moulding.title) %></div><div class="moulding info"><%= escape_javascript(@moulding.info) %></div>'; 

$('#someUniqueDiv').html(theHTML); 

很明顯,你會希望在對不良數據等幾個保障扔..但這應該讓你走上正軌。

2

您可以執行ajax調用來檢索數據,也可以使用HTML5數據屬性。

對於第二個解決方案,你會data-price屬性添加到您的選項標籤,所以它看起來像這樣:

<option value="1" data-price="123">123 589 698</option> 
<option value="2" data-price="456">897 896 887</option> 
<option value="3" data-price="789">876 234 567</option> 

然後,在你的JS文件:

$(document).ready(function() { 

    $('#order_item_moulding_1_id').change(function() { 
    var moulding_1_price = $(this).find('option:selected').attr('data-price'); 
    }); 

}); 
+0

謝謝,我使用`collection_select`來生成選擇標記。設置'data-price`屬性的正確方法是什麼? `html_options = {'data-price'=> ??? }` – freshest 2010-11-29 16:17:17