我有一个多选下拉框,有人建议我在 Rails 中创建一个 JSON api,该 API 返回给定商品列表的价格,但不确定如何实现,正在寻求指导。
orders.js.coffee
$("#item-select2").click ->
selectedItem = $(this)
#alert selectedItem.val()
if selectedItem.val()?
$.ajax([
"/items"
"/"
selectedItem.val()
".json"
].join("")).done (item) ->
$(".price").html item.price
else #no items selected
$(".price").html " "
对于选定的单个项目,价格显示正确,但如果我选择的项目多于我会得到 selectedItem.val()
返回 1,2,给出 items/1,2.json
表单
<%= simple_form_for(@order, remote: true) do |f| %>
<%= f.error_notification %>
<h3>Items</h3>
<%= f.association :items, collection: Item.all, label_method: :name, value_method: :id, prompt: "Choose an item", input_html: { id: 'item-select2' }, :wrapper_html => { :class => 'span6' } %>
<div class="product">
<div class="item"></div>
<div class="price"></div>
</div>
<div class="sub_total">
<div class="total">
</div>
</div>
<%= f.submit %>
<% end %>
我的项目应该动态添加,例如可以有超过 10 个项目。我应该在这里使用茧 gem 吗?
最佳答案
为什么不作为数据发送而不是在 URL 中发送?
$.ajax({
url: "/items.json",
data: { selectedItem: "[" + selectedItem.val() + "]" },
dataType: 'json'
}).done(function(data) {
// do something with the data
});
或者类似的东西。 Rails 仍然会解析 json 数据并提供 params[:selectedVal] 供您使用。如果 val() 以逗号分隔,则使用方括号。
关于javascript - Rails,JSON api 返回商品列表的价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020554/