我无法弄清楚,为什么我的javascript没有被执行(而且它真的没有被执行)。
/app/assets/javascripts/application.js:
//= require jquery
//= require bootstrap-sprockets
//= require turbolinks
//= require jquery_ujs
//= require_tree .
/app/controllers/project_controller.rb:
def upload
@projects = Project.all.order(updated_at: :desc)
@project = Project.find(params[:id])
respond_to do |format|
format.html
format.js {render layout: false}
end
end
/app/views/projects/show.html.erb:
<%= link_to project_upload_path, :project => @project.id, class: "btn btn-default" do %>
Upload
<%= glyph("plus") %>
<% end %>
/app/views/projects/upload.html.erb:
<div class="row">
<div class="col-xs-12">
<h2>Upload File to <%= @project.name %> project</h1>
</div>
<br>
<div class="col-xs-12">
<%= render :partial => "uploadform", :action => "savefile" %>
</div>
</div>
/app/views/projects/_uploadform.html.erb:
<%= form_for :upload, url: {action: "savefile"}, :multipart => true do |f| %>
<%= f.hidden_field(:project_id, :value => params[:id]) %>
<%= f.file_field :file, input_html: { hidden: true }, label: 'Upload Attachment' %>
<input id="file-display" class="input-large uneditable-input" type="text">
<%= f.submit "Save File", :class => "btn btn-default btn-file", :id => "upload-btn" %>
<% end %>
/app/views/projects/upload.js.erb:
$(document).on('ajax:success', function() {
alert("Test");
});
我尝试了一切。我在控制器中添加并删除了“{render layout:false}”。我在upload.js.erb中尝试了“page:change”和“turbolinks:load”(而不是“ajax:success”)。我尝试了“_uploadform.js.erb”中的所有Java-Ready函数(而不是“upload.js.erb”)。我在link_to(show.html.erb)中尝试了“remote:true” - 但是它只执行js.erb(只是警报出现了)。我还将Rails从4.2.1更新到4.2.7.1,并在application.js中尝试了“// = require jquery.turbolinks”(上面有所有文档就绪函数)。
正如您在我的日志中所看到的,似乎它没有响应Javascript:
Started GET "/projects/upload/20" for 127.0.0.1 at 2016-10-05 14:05:48 +0200
Processing by ProjectsController#upload as HTML
Parameters: {"id"=>"20"}
Project Load (0.0ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1 [["id", 20]]
Rendered projects/_uploadform.html.erb (0.0ms)
Rendered projects/upload.html.erb within layouts/application (2.4ms)
Completed 200 OK in 327ms (Views: 324.8ms | ActiveRecord: 0.0ms)
请帮帮我。我不明白为什么这不起作用。
答案 0 :(得分:0)
您需要告诉rails通过JavaScript执行表单的帖子。在日志中,您可以看到PagesController呈现HTML而不是JS
Processing by ProjectsController#upload as HTML
尝试添加:remote =&gt;对你的form_for帮助
是真的
<%= form_for :upload, url: {action: "savefile"}, :multipart => true, :remote => true do |f| %>
<%= f.hidden_field(:project_id, :value => params[:id]) %>
<%= f.file_field :file, input_html: { hidden: true }, label: 'Upload Attachment' %>
<input id="file-display" class="input-large uneditable-input" type="text">
<%= f.submit "Save File", :class => "btn btn-default btn-file", :id => "upload-btn" %>
<% end %>
有关详细信息,请参阅导轨指南http://guides.rubyonrails.org/working_with_javascript_in_rails.html#form-for。
答案 1 :(得分:0)