javascript - rails 5 : Can't redirect after JS call (DropZoneJS)

标签 javascript ruby-on-rails dropzone.js

我正在尝试在我的 Rails 5 应用程序中使用 DropZoneJS 实现拖放功能。我已完成上传文件,但当从 JavaScript 调用 Controller 时 View 不会刷新(与正常上传完美配合)。

代码(仅对案例重要的部分):

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 %>

第一个表单用于拖放,第二个表单用于常规上传(可以重定向)。

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 但它们都不起作用。

输出:

Processing by PrintingFilesController#new as JS

Parameters: {"utf8"=>"✓", "authenticity_token"=>"PBX2dbP8p+aZZXOkIIw1oFg3QZ02mDo+u+Z02NrBFCE+aNT3gWzwFjmQeGmcBcBItkg6l899iGIxuJljWDl+zA==", "printing_file"=>{"file"=>#, @original_filename="9.stl", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"printing_file[file]\"; filename=\"9.stl\"\r\nContent-Type: application/octet-stream\r\n">}}

Rendering printing_files/new.js.erb

Rendered printing_files/new.js.erb (1.0ms)

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

最佳答案

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

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

您可以更改该函数内的 Javascript 位置。

关于javascript - rails 5 : Can't redirect after JS call (DropZoneJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40178243/

相关文章:

ruby-on-rails - ActiveRecord oracle_enhanced 适配器无法加载 ruby​​-oci8 库

java - 如果使用 ruby​​ on rails、python 或 java 可以做得更好,为什么还要使用 php 框架进行编程?

javascript - 将第 3 方 JavaScript 库 (dropzone.js) 添加到 Aurelia

php - 如何使用 PHP 连接 Dropzone.js 上传的分块文件?

javascript - 通过 SystemJS 用于 NodeJS 的 TypeScript

javascript - 追加后事件监听器不起作用

ruby-on-rails - 为什么 Foreman 在我按下 Control-C 之前不输出一些东西?

javascript - 如何阻止 dropzone 删除我的文件?

javascript - 如何验证这种格式的电话号码

javascript - 简单的 jQuery .change 问题