Rails 4 尝试使用 AJAX 时将 JS 加载为纯文本
Rails 4 loads JS as plain text when trying to use AJAX
我正在尝试创建一个包含两列的简单页面。在左栏中,用户可以填写表格。在提交表单时,我想刷新右栏(通过 AJAX)并使用在控制器中创建的 @url 字符串填充 div。现在,表单提交根本不会触发我的 .js 页面上的代码——而是重定向离开页面并在浏览器中将我的 .js 作为纯文本加载。这应该很简单——我做错了什么?
在config/routes中:
root 'home#home'
post '/pixify', to: 'home#pixify', as: "pixify", format: 'js'
在家庭控制器中:
class HomeController < ApplicationController
respond_to :html, :js
skip_before_action :verify_authenticity_token
def home
end
def pixify
@url = "http://example-url.com"
respond_to do |format|
format.js { render :layout => false }
end
end
end
在views/home/home.html.haml:
%div#container
%div.left-column
= form_tag pixify_path, :remote => true do
%fieldset
%ul
%li
%label{:for => "url-id"} URL ID:
%input{:type => "text", :name => "url-id"}
%input{:type => "submit", :value => "Generate url", :class => "button"}
%div.right-column
%div#generated-url
在views/home/pixify.js.erb:
console.log("This is working"); // but it isn't
$('#generated-url').html('http://www.justanexample.com');
我明白了! This answer 让我走上了正确的道路。由于 application.html.erb 中的 javascript 标记,jquery_ujs 无法正常工作。结果我需要改变这个:
<%= javascript_include_tag :defaults %>
对此:
<%= javascript_include_tag 'application' %>
我在对一个单独的模板问题进行故障排除时更改了该行,但忘记将其切换回来。我还从控制器中删除了渲染语句(根据@VenkatCh 的回答——谢谢!),现在一切正常。
respond_to do |format|
format.js
end
如果您的 application.js 文件中没有包含 jquery_ujs 库,js.erb 文件将呈现为文本:
//= require jquery
//= require jquery_ujs
我打赌这就是 'default' 和 'application' 文件之间的区别。
并且您的 gemfile 中需要以下 gem:
gem 'jquery-rails'
gem 'jquery-ui-rails'
我正在尝试创建一个包含两列的简单页面。在左栏中,用户可以填写表格。在提交表单时,我想刷新右栏(通过 AJAX)并使用在控制器中创建的 @url 字符串填充 div。现在,表单提交根本不会触发我的 .js 页面上的代码——而是重定向离开页面并在浏览器中将我的 .js 作为纯文本加载。这应该很简单——我做错了什么?
在config/routes中:
root 'home#home'
post '/pixify', to: 'home#pixify', as: "pixify", format: 'js'
在家庭控制器中:
class HomeController < ApplicationController
respond_to :html, :js
skip_before_action :verify_authenticity_token
def home
end
def pixify
@url = "http://example-url.com"
respond_to do |format|
format.js { render :layout => false }
end
end
end
在views/home/home.html.haml:
%div#container
%div.left-column
= form_tag pixify_path, :remote => true do
%fieldset
%ul
%li
%label{:for => "url-id"} URL ID:
%input{:type => "text", :name => "url-id"}
%input{:type => "submit", :value => "Generate url", :class => "button"}
%div.right-column
%div#generated-url
在views/home/pixify.js.erb:
console.log("This is working"); // but it isn't
$('#generated-url').html('http://www.justanexample.com');
我明白了! This answer 让我走上了正确的道路。由于 application.html.erb 中的 javascript 标记,jquery_ujs 无法正常工作。结果我需要改变这个:
<%= javascript_include_tag :defaults %>
对此:
<%= javascript_include_tag 'application' %>
我在对一个单独的模板问题进行故障排除时更改了该行,但忘记将其切换回来。我还从控制器中删除了渲染语句(根据@VenkatCh 的回答——谢谢!),现在一切正常。
respond_to do |format|
format.js
end
js.erb 文件将呈现为文本:
//= require jquery
//= require jquery_ujs
我打赌这就是 'default' 和 'application' 文件之间的区别。
并且您的 gemfile 中需要以下 gem:
gem 'jquery-rails'
gem 'jquery-ui-rails'