【问题标题】:Rails 3 AJAX page redirecting after uploading image上传图片后Rails 3 AJAX页面重定向
【发布时间】:2012-01-31 10:15:00
【问题描述】:

我正在使用 AJAX 上传图像(使用carrierwave gem),并希望在上传后显示图像而不刷新或重定向页面。目前,在我上传图片后,它会重定向到 /images 而不是停留在 / 主页上。

image_controller.rb:

def create
  @image = Image.new(params[:image])
  respond_to do |format|
    if @image.save
     format.js
    end
  end
end

_upload.html.erb:

<%= form_for @image, :html => { :multipart => true }, :remote => true do |f|%>
  <p>
  <%= f.file_field :image %>
  </p>
  <p><%= f.submit "Upload image", :class => 'btn primary', :id => 'image-upload' %></p>
<% end %>  

create.js.erb:

$('images-show').replaceWith('<%=j render 'shared/show_image' %>');

如何防止图片上传后重定向到 /images?

【问题讨论】:

  • 我不知道你的问题的答案,但有点友好的建议。渲染部分时始终使用 escape_javascript 以避免恶意代码。请参阅stackoverflow.com/questions/1620113/… 了解更多信息。所以应该是$('images-show').html('&lt;%=escape_javascript(render 'shared/show_image') %&gt;');
  • 感谢您的建议!不知道 escape_javascript 到底是做什么的。我在 API 文档中读到 j 可以用来代替 escape_javascipt,这是真的吗?
  • 它正在执行一个 POST 请求。我如何告诉它做一个 GET 请求?

标签: ruby-on-rails ajax ruby-on-rails-3 ruby-on-rails-3.1


【解决方案1】:

对于初学者,请确保您的 Gemfile 中有 gem 'jquery-rails'。然后确保您的 html 文档 application.html.erb 的头部有 &lt;%= javascript_include_tag "application" %&gt; 并且您包含的文件 application.js 有以下行:

//= require jquery
//= require jquery_ujs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多