Rails 5:JS调用后无法重定向(DropZoneJS)

时间:2016-10-21 13:42:20

标签: javascript ruby-on-rails dropzone.js

我正在尝试使用 Rails 5 应用中的 DropZoneJS 实现拖放功能。我完成了上传文件,但是当从JavaScript调用控制器时,视图不会刷新(与普通上传完美配合)。

代码(只有与案件有关的部分):

index.html.erb

<%= form_for(:printing_file, url: new_printing_file_path, html: {method: :post, class: "dragdropzone"} ) do |f| %>
    <div>Drag&Drop a file here</div>
<% end %>

<%= form_for(:printing_file, url: new_printing_file_path, html: {method: :post}) do |f| %>
    <%= f.file_field :file, class: "printing-file-upload-field", onchange: "this.form.submit()" %>
<% end %>

Drag&amp; Drop的第一个表单,常规上传的第二个表单(重定向正常)。

printing_files.coffee

$(document).ready ->
  Dropzone.autoDiscover = false
  dropzone = new Dropzone('.dragdropzone',
    paramName: 'printing_file[file]'
    addRemoveLinks: false
    headers: { 'Accept': 'application/javascript' })

printing_files_controller.rb

def new
  @printing_file = PrintingFile.new(printing_file_params)
  @printing_file.user = current_user
  @printing_file.name = printing_file_params[:file].original_filename
  if @printing_file.save
    respond_to do |format|
      format.html { redirect_to files_path, notice: "File was correctly uploaded." }
      format.js
    end
  else
    redirect_to files_path, alert: "There was an error while uploading file."
  end
end

new.js.erb

console.log("This is never printed");
window.location = "<%= files_path() %>";

我也尝试了printing_files_controller.rb这里找到的几个选项,例如render js,但都没有。

输出:

  

PrintingFilesController处理#new为JS

     

参数:{&#34; utf8&#34; =&gt;&#34;✓&#34;,&#34; authenticity_token&#34; =&gt;&#34; PBX2dbP8p + aZZXOkIIw1oFg3QZ02mDo + u + Z02NrBFCE + aNT3gWzwFjmQeGmcBcBItkg6l899iGIxuJljWDl + zA ==&#34;,&#34; printing_file&#34; =&gt; {&#34; file&#34; =&gt;#,@ original_filename =&#34; 9.stl&#34;,@ content_type =&#34; application / octet-stream&#34;,@ header =&#34; Content-Disposition:form-data;命名= \&#34; printing_file [文件] \&#34 ;; filename = \&#34; 9.stl \&#34; \ r \ nConContent-Type:application / octet-stream \ r \ n&#34;&gt;}}

     

渲染printing_files / new.js.erb

     

渲染了printing_files / new.js.erb(1.0ms)

请注意,js文件正在渲染,但浏览器控制台没有显示任何内容。

1 个答案:

答案 0 :(得分:1)

我相信你正在寻找Dropzone的成功参数:

$(document).ready ->
  Dropzone.autoDiscover = false
  dropzone = new Dropzone('.dragdropzone',
    paramName: 'printing_file[file]'
    addRemoveLinks: false
    headers: { 'Accept': 'application/javascript' })
    success: () -> location.reload()

您可以更改该功能中的Javascript位置。