I'm using rails version 3.2.6 and I'm trying to pass a Javascript variable to another page "Test10". I have the following code in the view:
<script>
var message = "hello world!";
</script>
<%= link_to "Go!", Test10_path(), :with => "'message='+ message" %>
The parameter is not passed to Test10. I have the following in the Test10 controller:
def Test10
@hello = params[message]
end
Is this the right way to pass a Javascript variable to my rails controller? It is not working. I'd appreciate any pointers. Thanks!
<%= link_to "Go!", Test10_path(), :id => "my_link" %>
<script>
var message = 'test';
var url = $('#my_link').attr('href') + '?message=' + message;
$('#my_link').attr('href', url);
</script>
Something like this should work. Although most of the time, it's best to pass params by using forms instead ...
You can't do this. JavaScript and Ruby code execute in completely different contexts, JavaScript on the client and Ruby on the server.
In general, if you want to communicate a value from the client to the server, you need to do so either by posting it back in a form or as part of a query string, or via AJAX.
In your specific example, you'll have to write some JavaScript which selects the anchor tag and appends the contents of the message
variable to the anchor tag's query string. Something like the following:
<script>
var message = "hello world!";
// Select your anchor tag
var link = $('a#my-link');
// Append your message to the link's href attribute
link.attr('href', link.attr('href') + "?message=" + message);
</script>
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.