2012-01-31 63 views
1

我使用AJAX上傳圖片(使用carrierwave gem)並希望在上傳後顯示圖片而不刷新或重定向頁面。目前,我上傳圖片後重定向到/圖片,而不是保留在/主頁上。Rails 3上傳圖片後重定向AJAX頁面

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' %>'); 

如何防止重定向到/圖片上傳圖片後?

+0

我不知道答案,你的問題,但一點點友好的建議。渲染局部時總是使用escape_javascript來避免惡意代碼。有關更多信息,請參閱http://stackoverflow.com/questions/1620113/why-escape-javascript-before-rendering-a-partial。所以它應該是'$('images-show')。html('<%= escape_javascript(render'shared/show_image')%>');' – Ashitaka 2012-01-31 10:53:40

+0

感謝您的建議!沒有確切知道escape_javascript的功能。我在API文檔中讀到j可以用來代替escape_javascipt,這是真的嗎? – ramz15 2012-01-31 11:56:14

+0

它正在執行POST請求。我如何告訴它執行GET請求? – ramz15 2012-01-31 17:15:17

回答

1

對於初學者,請確保您的Gemfile中有gem 'jquery-rails'。然後確保你在你的HTML文檔application.html.erb的頭,要包括的文件有<%= javascript_include_tag "application" %>application.js有行:

//= require jquery 
//= require jquery_ujs