2015-10-06 71 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。