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. Here is my code
def index
render :js => "alert('Hello Rails');"
end
It renders the same string "alert('Hello Rails');" for me in view instead of a alert message. Im in Rails 3 and as Rails guide the code looks ok.
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. jQuery ajax calls in the @Erez answer also wrap response with <script>
internally.
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)
You are rendering JS ok. The problem is with the browser which receives this JS and displays it as plain text.
Try sending an AJAX request with (using JQuery here):
$.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.
The short version for this would be
$.getScript('/index/url');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.