简体   繁体   English

如何使用Rails和Ajax加载div?

[英]How to load a div with Rails and ajax?

I have an index page full of products (products controller), and I can create orders by clicking on 'Order' button, which leads a user to the 'new' action of the order controller with the product id passed as a parameter. 我有一个充满产品(产品控制器)的索引页面,我可以通过单击“订单”按钮来创建订单,这会将用户引导到订单控制器的“新”操作,并将产品ID作为参数传递。

  def new
    @order = Order.new
    @product = Product.find(params[:product])
  end

There the user can select the quantity he wants and finally create the order. 用户可以在那里选择所需数量并最终创建订单。

However I would like to make a modal window pop up instead when clicking 'order', with the form from the 'new order' page in it. 但是,我想在单击“订单”时弹出一个模式窗口,其中带有“新订单”页面中的表格。 So I've added the data-remote attribute to my Order button: 因此,我将data-remote属性添加到“订购”按钮:

<%= link_to('Order', new_order_path(product: product), class: "btn btn-order", remote: true) %>

Updated thee controller: 更新了您的控制器:

def new
    @order = Order.new
    @product = Product.find(params[:product])

    respond_to do |format|
      format.html
      format.js
    end
  end

and created the new.js.erb file, that opens my modal window 并创建了new.js.erb文件,该文件打开了我的模式窗口

function openModal = somecode...

But how do I grab the html of a FORM which lies beyond the link? 但是,如何获取超出链接范围的FORM的html? I don't want to render partials, I just want the form code to be pasted into the .html('...') of my modal window! 我不想渲染部分,只希望将表单代码粘贴到我的模式窗口的.html('...')中!

Thanks! 谢谢!

You can use jQuery to add the contents of the form to the DOM by rendering it as a partial in your new.js.erb file like so: 您可以使用jQuery将表单内容添加到DOM中,方法是将其作为部分内容呈现在new.js.erb文件中,如下所示:

$('#modal_id').html('<%= escape_javascript(render(partial: "path/to/partial", object: @instance_variable)) %>');

EDIT: On a second read of your question, I see you mentioned that you do not wish to render partials, you could therefore simply have the form code directly in your new view; 编辑:在二读您的问题时,我看到您提到您不希望呈现部分内容,因此您可以直接在new视图中直接使用表单代码。 something like this: 像这样的东西:

var form_html = '<form>...</form>';
$('#modal_id').html(form_html);

I hope this helps! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM