简体   繁体   English

香草javascript渲染平面文本铁路

[英]vanilla javascript rendering plane text RAILS

I have been using vanilla javascript and im just rendering a simple alert message but it renders the JS code as plane string in view. 我一直在使用vanilla javascript,我只是渲染一个简单的警报消息,但它将JS代码呈现为视图中的平面字符串。 Here is my code 这是我的代码

def index
render :js => "alert('Hello Rails');"
end

It renders the same string "alert('Hello Rails');" 它呈现相同的字符串“alert('Hello Rails');” for me in view instead of a alert message. 对于我而言,而不是警报消息。 Im in Rails 3 and as Rails guide the code looks ok. 我在Rails 3和Rails 指南中代码看起来不错。

Any answers would be appreciated. 任何答案将不胜感激。 Thanks 谢谢

Compare two following snippets: 比较以下两个片段:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
    alert('Hello Rails');
    </script>
</body>
</html>

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    alert('Hello Rails');
</body>
</html>

First one generates alert message, second just shows the the string. 第一个生成警报消息,第二个只显示字符串。 Browsers do not execute JS code unless it is wrapped with <script> tag. 浏览器不执行JS代码,除非它包含<script>标记。 jQuery ajax calls in the @Erez answer also wrap response with <script> internally. @Erez答案中的jQuery ajax调用也在内部用<script>包装响应。

So if you access your action directly try to wrap it with <script> , or, better, use javascript_tag helper (http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag) 因此,如果您直接访问您的操作,请尝试使用<script>包装它,或者更好地使用javascript_tag帮助程序(http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag)

You are rendering JS ok. 你正在渲染JS好。 The problem is with the browser which receives this JS and displays it as plain text. 问题在于接收此JS的浏览器并将其显示为纯文本。

Try sending an AJAX request with (using JQuery here): 尝试发送一个AJAX请求(在这里使用JQuery):

$.ajax(url: '/index/url', type: 'GET', dataType: 'script')

Note that the dataType is set to script, meaning JQuery will execute the returned text as JS. 请注意,dataType设置为script,这意味着JQuery将以JS的形式执行返回的文本。

The short version for this would be 这个的简短版本将是

$.getScript('/index/url');

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

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