【问题标题】:url_for and remote: trueurl_for 和远程:true
【发布时间】:2015-01-26 11:14:34
【问题描述】:

我遇到了 Rails 的问题。我想要一个在单击时呈现部分视图的选择表单。我希望部分视图在不刷新整个文档(Ajax)的情况下有效,但似乎remote: true 对我不起作用......

我目前拥有的并刷新整个文档:

= form_tag url_for(action: :index), method: 'get' do
    //Storing some informations in html fields for further use
    - shops_array = @shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
    = select_tag :shop_id, options_for_select(shops_array, @shop_id), prompt: "Your shop :", data: {submit_on_change: true}

我尝试过的:

= form_tag url_for(action: :index), remote: true, method: 'get' do
    //Storing some informations in html fields for further use
    - shops_array = @shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
    = select_tag :shop_id, options_for_select(shops_array, @shop_id), prompt: "Your shop :", data: {submit_on_change: true}

如何将remote: true 选项与url_for 一起应用?如果不可能,我可以使用一些帮助来寻找解决方法。

【问题讨论】:

    标签: ruby-on-rails ruby ajax forms


    【解决方案1】:

    根据docs,您可以为form_tag 方法指定remote 选项,如下所示:

    form_tag(url_for(controller: :charmander, action: :ember), remote: true, method: :get, class: 'pokemon-form') do
      # form logic
    end
    

    但是,这只会在提交整个表单时触发ajax:success事件。

    从您的问题来看,在我看来,当您的选择值发生变化时,您想重新渲染一些部分内容。我不确定您如何使用 submit_on_change 数据属性,但如果我假设您在选择值更改时提交整个表单是正确的,那么您需要做的就是监听 ajax:success 事件对于整个表单,如下所示:

    $('.pokemon-form').on('ajax:success', function (event, data, status, xhr) {
      // Do something with data, which would be the rendered partial returned
      // from the server call.
    });
    

    【讨论】:

      【解决方案2】:

      最终使用了 onclick 和 JavaScript 函数。虽然它可能不是最好的解决方案,也不是更漂亮的解决方案,但它对我来说就像一种魅力。

      = select_tag :shop_id, options_for_select(shops_array, @shop_id), prompt: "Your shop :", onclick: 'ajaxSelectedShop('+String(8)+')'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 2013-03-15
        相关资源
        最近更新 更多