Ruby on Rails – 使用AJAX获取数据的jQuery
我有以下型号:
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标记:
Select a moulding 1 123 589 698 897 896 887 876 234 567
这是javascript文件的一部分:
$(document).ready(function () { $('#order_item_moulding_1_id').change(function () { var moulding_1_price = ; }); });
如何使用Ajax设置变量moulding_1_price?
如果你想通过ajax在rails控制器中完成它,你只需将每个选项的值设置为你正在查找的模型的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 = '<%= escape_javascript(@moulding.title) %><%= escape_javascript(@moulding.info) %>'; $('#someUniqueDiv').html(theHTML);
显然,你会想要对坏数据等提出一些保护措施……但这应该会让你走上正轨。
您可以执行ajax调用来检索数据,也可以使用HTML5数据属性。
对于第二个解决方案,您可以将data-price
属性添加到选项标记中,因此它看起来像这样:
然后,在您的JS文件中:
$(document).ready(function () { $('#order_item_moulding_1_id').change(function () { var moulding_1_price = $(this).find('option:selected').attr('data-price'); }); });