2015-10-06 66 views
0

我使用Rails 4和Dropzone.js來拖放文件並在表單提交上上傳它們。我不知道爲什麼我不能得到這個工作,但我試圖在表單提交到某個頁面後重定向,但它沒有這樣做(一切都可以正常保存)。無法獲取頁面重定向?

這裏是我的代碼:

項目/ new.html.haml> _form.html.haml

= form_for @item, validate: true, 
    html: {id: 'item-form', class: 'form-horizontal form', multipart: true} do |f| 

    = f.text_field :name 

    %main#image-preview 
     #dropzone 
      .fallback 
       = f.file_field :image, multiple: false 

    = f.submit 'Done', id: 'item-submit' 

items.coffee

Dropzone.autoDiscover = false 

    if document.getElementById('item-form') 
    dropzone = new Dropzone('#item-form', 
     maxFiles: 1 
     maxFilesize: 1 
     paramName: 'item[image]' 
     headers: "X-CSRF-Token" : $('meta[name="csrf-token"]').attr('content') 
     addRemoveLinks: true 
     clickable: '#image-preview' 
     previewsContainer: '#image-preview' 
     thumbnailWidth: 200 
     thumbnailHeight: 200 
     autoProcessQueue: false 
     uploadMultiple: false) 

    $('#item-submit').on 'click', (e) -> 
     e.preventDefault() 
     e.stopPropagation() 
     if dropzone.getQueuedFiles().length > 0 
     dropzone.processQueue() 
     else 
     $getScript '/items' 
     return 

items_controller.rb

def continue 
    @item = Item.find(params[:id]) 
    if @item.user_id == current_user.id 
     respond_to do |format| 
     format.html 
     format.xml 
     format.json { render :json => {} } 
     end 
    end 
    end 

    def new 
    @item = current_user.items.build 
    end 

    def create 
    @item = current_user.items.build(item_params) 

    respond_to do |format| 
     if @item.save 
     format.json { render :json => "window.location = #{post_continue_item_path(@item).to_json}" } 
     else 
     format.html { render :new } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

的routes.rb

resources :items do 
    get '/post/continue', to: 'items#continue', on: :member 
end 

日誌

Started POST "/items" for 127.0.0.1 at 2015-10-06 12:23:35 -0700 
Processing by ItemsController#create as JSON 
............ 
Completed 200 OK in 1786ms (Views: 0.2ms | ActiveRecord: 10.6ms) 

不確定在哪裏與此,所以如何重定向時,它給我一個JSON調用?

回答

0

JSON不是Javascript。它旨在傳遞一些數據,而不是工作代碼。用瀏覽器的開發工具檢查響應,你會看到你的'window.location'腳本很好地包裝,基本上無法做任何事情 - 它應該只是一個字符串。

如果您想要一個純粹的傳統HTTP重定向,您應該查看redirect_to Rails方法作爲唯一的響應,並且在實際需要重定向時不會嘗試呈現JSON。