【问题标题】:Load form object on fetching from ajax从 ajax 获取时加载表单对象
【发布时间】:2018-09-19 00:31:47
【问题描述】:

我有一个呈现部分“表单”的表单。

= form_for(@booking, :as => :booking, :url => admin_bookings_path, :html => { :multipart => true }) do |f|
  = render partial: "form", locals: { f: f }

在部分表单中,另一个部分再次基于 new_record 呈现?

- if f.object.new_record?
  #extra-products
    = render partial: 'new_booking_extra_product', locals: { f: f }
- else
  = render partial: 'extra_product', locals: { f: f }

在 bookings#new 中,当用户选择特定的 car_id 时,我想通过 ajax 显示与之相关的产品。为此,我使用 ajax 向 bookings#fetch_extra_product 发出请求。

# Ajax request to fetch product
$('#booking_car_id').on('change', function(e){
    var selectedCarId = $("#booking_car_id option:selected").val();
    var url = "/admin/bookings/" + selectedCarId + "/fetch_extra_product";

    $.ajax(url,{
      type: 'GET',
      success: function(msg){
      },
      error: function(msg) {
        console.log("Error!!!");
      }
    });
  });

# Bookings#fetch_extra_product
def fetch_extra_product
    @car_id = params[:car_id] || Car.all.order('id desc').first.id
    @extra_product = Car.find(@car_id).extra_products

    respond_to do |format|
      format.js
    end
end

fetch_extra_product.js.erb 如下所示:

$('#extra-products').html('$("<%= j render(:partial => 'new_booking_extra_product', :locals => {:f => f}) %>")');

但表单对象 (f) 在此状态下未定义。获取对象或解决此问题的最佳方法是什么?

【问题讨论】:

  • 你能用_new_booking_extra_product.html.erb code更新问题吗?
  • 这是未定义的,因为您正在从客户端执行 ajax 请求。 'f' 对象仅在第一次请求期间存在于服务器端。

标签: javascript ruby-on-rails ruby ajax ruby-on-rails-5


【解决方案1】:

当收到 Ajax 请求时,您需要在服务器端呈现带有关联产品的局部视图。然后,您可以将该部分的 HTML 作为响应的一部分发送,并使用 Ajax success 回调将部分视图附加到您想要的 DOM。然后您可以(在您的控制器中)编写如下代码:

def fetch_extra_product

  # Unless you're using @car_id in a view or something, I'd just
  # just use a local variable instead of an instance variable
  #
  car_id = params[:car_id] || Car.all.order('id desc').first.id
  @extra_products = Car.find(car_id).extra_products

  respond_to do |format|
    format.js { render partial: 'extra_products_div', status: :ok }
  end

那么你的部分代码是这样的:

<div class="extra-products">
  <% @extra_products.each do |product| %>
    <h2><%= product.name %></h2>
    ...
  <% end %>
</div>

这样,您的 JavaScript 就可以按照以下方式运行:

$.ajax(url, {
  type: 'GET',
  success: function(msg) {
    $('#foo').attach(msg);
  },
  error: function(msg) {
    console.log('Error!!!');
  }
});

另一条评论:如果您的 API 仅通过 Ajax 获取对该路由的请求,则不需要 respond_to 块。在这种情况下,您只需将render partial: 'extra_products_div', status: :ok 放在您所在的行下方 定义@extra_products

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 2021-01-13
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多