开发者

Rails: How do I use a javascript variable outside <script.../> but inside the view?

开发者 https://www.devze.com 2022-12-19 18:34 出处:网络
In a view I have a script (javascript) that declares a variable after some deep processing. How can I use that variable outside the script boundaries in the same view开发者_Python百科 page?

In a view I have a script (javascript) that declares a variable after some deep processing. How can I use that variable outside the script boundaries in the same view开发者_Python百科 page?

some_view.html.erb

<script>var seq = Sortable.sequence('list');</script>

# How to do this? Is it possible?

<%= sortable_element "list",
  :update => "order",
  :complete=> visual_effect(:highlight, "list"),
  :scroll => 'list',
  :url=>{:action=>"order", :order_init => seq} %>

Thank you!


It's not possible becasue Rails is a server-side language and javascript is executed on client side.

What you are looking for is AJAX functionality (asynchronous JavaScript)


If it is truly javascript that declares the variable after JavaScript processing, then you need to work the other way around. Like this (Move the script block below the HTML or this example will fail):

<h2> Hello, my name is <span id="name"></span></h2>

<script type="text/javascript">
   var name = "World";
   document.getElementById('name').innerHTML = name;
</script>

That way after the script runs, the name would be replaced in the HTML on the client side.

0

精彩评论

暂无评论...
验证码 换一张
取 消