无法获取重定向页面?

时间:2015-10-06 19:37:22

标签: ruby-on-rails ruby-on-rails-4

我正在使用Rails 4和Dropzone.js拖放文件并在表单提交时上传它们。我不知道为什么我不能让这个工作,但是我想在表单提交到某个页面之后重定向但是它没有这样做(尽管一切都保存正确)。

这是我的代码:

  

items / 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电话时如何重定向?

1 个答案:

答案 0 :(得分:0)

JSON不是Javascript。它旨在传递一些数据,而不是工作代码。使用浏览器的开发人员工具查看回复,您会看到自己的“window.location'脚本很好地包装,基本上无法做任何事情 - 它应该只是一个字符串。

如果你想要一个纯粹的,经典的HTTP重定向,你应该将redirect_to Rails方法作为唯一的响应,并且在你真正需要重定向时永远不要尝试渲染JSON。

相关问题