简体   繁体   English

在使用AJAX的Rails 4中,如何成功更新特定的div?

[英]In Rails 4 using AJAX, how do I update a particular div on success?

I have a bunch of images and when I upload another using AJAX, I need to refresh the div that the images are held in. In Rails 3.2 I used to be able to use a partial and render_to_string in the controller and send JSON back with the new html, but that method does not seem to work in Rails 4. 我有一堆图像,当我使用AJAX上传另一个图像时,我需要刷新保存图像的div。在Rails 3.2中,我曾经能够在控制器中使用partial和render_to_string并使用新的html,但是该方法似乎在Rails 4中不起作用。

I have a partial called images.html.haml that needs a local variable 'user' 我有一个名为images.html.haml的局部文件,需要局部变量'user'

I have a controller that uses the following: 我有一个使用以下内容的控制器:

respond_to do |format|
  html = render_to_string('_images.html.haml', locals => {'user' => user}) 
  format.json {render :json => {:html => html} }
end

However, when I use this method, not only the partial, but the partial within the application layout gets rendered. 但是,当我使用此方法时,不仅会渲染部分,而且还会渲染应用程序布局内的部分。 I did some searching to find that there is now a :partial key, so I tried that but then Rails couldn't find the partial. 我做了一些搜索,发现现在有一个:partial键,所以我尝试了一下,但是Rails找不到部分键。 Is there a better way to do this that is supported by Rails 4? Rails 4是否有更好的方法来做到这一点?

这应该为您工作:

html = render_to_string(partial: 'images', locals: {user: user})

您可以尝试一下,让我知道是否可行吗?

render_to_string(:partial => '_images.html.haml', :locals => {'user' => user}, :layout => false)

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

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