Rails 4-强制浏览器执行JavaScript响应,而不是显示文本 [英] Rails 4 - force browser to execute javascript response instead of displaying text

查看:31
本文介绍了Rails 4-强制浏览器执行JavaScript响应,而不是显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 4应用程序,我需要在其中强制控制器发送对所有HTML或JS请求的JS响应.由于某些原因,当控制器收到html请求时(例如,当用户通过键入url发出请求时),浏览器将响应显示为文本,而不是执行代码.

I have a Rails 4 application where I need to force the controller to send a js response to all requests, html or js. For some reason, the browser is displaying the response as text instead of executing the code when the controller receives an html request (for example, when the user makes a request by typing in the url).

控制器:

def action
  render :template => 'sessions/home.js.erb', :content_type => "text/javascript"
end

sessions/home.js.erb:

$("#button").on("click", function(){
  alert("got here");
});

浏览器无需绑定#button,而是仅将home.js.erb中的代码显示为文本.

Instead of binding #button, the browser simply displays the code from home.js.erb as text.

我在控制器中尝试了以下选项,但结果是相同的-浏览器只显示文本而不是执行代码:

I've tried the following options in the controller but the results are the same - the browser just presents the text vs executing the code:

render js: "alert('got here')";

render :format => :js, :template => 'sessions/home.js.erb'

respond_to do |format|
   format.html {render :template => 'sessions/home.js.erb', :content_type => 'text/javascript'}
end

respond_to do |format|
   format.html {render :template => 'sessions/home.js.erb', :content_type => 'application/javascript'}
end

有人可以帮我弄清楚我需要做些什么才能使浏览器执行javascript吗?

Can somebody help me figure out what I need to do in order to get the browser to execute the javascript?

推荐答案

铁路可以为您提供

Rails can deliver you code, but it's up to you to ensure that the code is loaded and executed on the clientside, otherwise it really is just text.

jQuery正是为此提供了一些方便的助手

Jquery has a few handy helpers just for this thing

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

这将加载并执行Javascript文件.或者您可以使用

This will Load and Execute a Javascript file. Or you can use

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});

两个示例均从Jquery api文档复制而来. http://api.jquery.com/jquery.ajax/ http://api.jquery.com/jquery.getscript/

Both examples copied from the Jquery api docs. http://api.jquery.com/jquery.ajax/ and http://api.jquery.com/jquery.getscript/

这篇关于Rails 4-强制浏览器执行JavaScript响应,而不是显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆