简体   繁体   English

Rails 4 react_to javascript

[英]Rails 4 respond_to javascript

I have a simple PagesController with a 'homepage' method. 我有一个带有'homepage'方法的简单PagesController。 I just want the method to respond to my homepage.js.erb template file which is containing a simple console.log("Hello World!"); 我只希望该方法响应包含一个简单console.log("Hello World!"); homepage.js.erb模板文件console.log("Hello World!"); So i wrote respond_to do |format| format.js format.html end 所以我写了respond_to do |format| format.js format.html end respond_to do |format| format.js format.html end in my homepage method but it does nothing. respond_to do |format| format.js format.html end以我的主页方法respond_to do |format| format.js format.html end ,但是它什么也没做。 ( no hello world in my chrome console ). (我的chrome控制台中没有hello world )。 If i remove the format.html rails throw me this error "ActionController::UnknownFormat" . 如果我删除format.html轨道扔我这个错误"ActionController::UnknownFormat"

Is it a problem with turbolinks? Turbolink是否有问题? how can i do? 我能怎么做?

Thanks JD 谢谢JD

Turbolinks sends request as Html, So the js file wont get rendered but HTML one and on Client side turbolinks just replaces body with new content and updates URL. Turbolinks以Html发送请求,因此不会渲染js文件,但是HTML one和在客户端的Turbolinks只是用新内容替换了正文并更新了URL。

If you want to render you js.erb file then you need to initiate js request not html. 如果要呈现js.erb文件,则需要启动js请求而不是html。 just write remote true in link_to. 只需在link_to中写入remote true。

Example

= link_to 'XYZ', url, :remote => true

Or if you want to execute js code on browser for HTML request then you need to write your JavaScript code inside you HTML file(format.html) 或者,如果您想在浏览器上执行HTML代码的js代码,则需要在HTML文件(format.html)中编写JavaScript代码

Example: 例:

javascript:
  console.log("Hello World!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM