0

我知道这可能是一个常见问题,但我一直在寻找几个小时没有运气,所以我想我会问。

如何在输入字段更改时通过 ajax 提交表单?我有一个表单,除其他外,用户从下拉列表中选择产品,然后我希望该产品的图片立即通过 ajax 显示。这就是我所拥有的:

<%= f.association :product, collection: @products %>
<div id="prodPicture">...</div>

我认为正确的方法可能是添加 remote: true 和 url,但我还没有让它工作。

<%= f.association :product, collection: @products, remote: true, url: url_for(controller: 'quotes', action: 'getdata'), type: 'JSON' %>

这是将 ajax 事件添加到表单字段更改的正确方法吗?

提前感谢您的帮助!

4

3 回答 3

1

你绑定到下拉更改事件

$("#idofdropdown").change(function(){
var selection = $(this).val() // always gets selected value by default
$.ajax()//and so forth

});
于 2013-11-06T16:07:43.003 回答
0

您可以在页面上创建隐藏img元素,然后添加一些 JS 代码: ("#idofdropdown").change(function(){ $('#id_image').attr('src', PRODUCTS_IMAGES[parseInt($(this).val())] });

然后显示img。

在哪里 var PRODUCTS_IMAGES = #{@products.collect{|e| [e.id, e.file.url]}.to_json};

类似的东西......基本上你有一个JS字典,在下拉列表和img src中选择了ID。

于 2013-11-06T17:23:54.563 回答
0

您想在更改收藏时立即显示图片吗?

您可以通过两种方式做到这一点:

1.添加data-image-url选项

最好的方法是将图像 url 添加到选项使用中data-image-url

<%= f.association :product, include_blank: false, label: 'Product', input_html: {class: 'product_select' do %>
  <%= f.select :product, @products.map{|a| [a.name, a.id, {"data-image-url" => a.image_url}]} %>
<% end %>

并使用这个 javascript:

<script type="text/javascript">
  $(".product_select").change(function(){
    var selection = $(this).find(':selected').data("imageUrl");   //The product image url
    $('#prodPicture').html("<img src='" + selection + "' />")
  });
</script>

2.使用ajax

ajax javascript 使用帖子:

<script type="text/javascript">
  $(".product_select").change(function(){
    var selection = $(this).val();
    $.post("/products/return_image_url",
            {product_id: selection},
            function(data) {
               if (data != null) {
                  $('#prodPicture').html("<img src='" + data + "' />")
               }
             }
           )
  });
</script>

以及关于此的红宝石行动:

def return_image_url
  product = Product.find(params[:product_id])
  ...
  respond_to do |format|
    format.json { render :json => product.image_url }
  end
end

而且我认为你最好使用Add data-image-url to option.

我想写一些关于remote: true

remote: true来自jquery_ujs, 可以用在link_to,button_tosubmit. 它必须有一个链接。当您更改选择或单选等时,无法使用remote: true.

remote: true您可以在指南中了解更多信息:http: //guides.rubyonrails.org/working_with_javascript_in_rails.html

于 2013-11-06T18:05:26.410 回答