javascript - Rails,JSON api 返回商品列表的价格

标签 javascript jquery ruby-on-rails ajax ruby-on-rails-4

我有一个多选下拉框,有人建议我在 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/

相关文章:

javascript - Ajax在php中提交表单序列化数据为空

ruby-on-rails - 解决 PG::GroupingError: ERROR

javascript - 在 bootstrap 中运行自定义 jquery 文件但失败

css - 如何在 application.css 中要求特定文件

ruby-on-rails - 用户模型声明性授权 'if_attribute'问题

javascript - 使用 sortBy 方法排序在下划线中不起作用

javascript - 使用内联动画关键帧定义?

javascript - KnockoutJS/jQuery UI 可排序冲突

javascript - 将更改格式功能添加到 "Find and Replace"功能的脚本

jquery - twitter.typeahead.js 在 asp.net core mvc 项目中不起作用