将变量从Javascript传递到Ruby on Rails

编程入门 行业动态 更新时间:2024-10-10 19:23:56
本文介绍了将变量从Javascript传递到Ruby on Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在rails中你可以这样做:

In rails you can do this:

<% name = @user.name %> <script> var name = <%= name%>; alert(name); //prints the name of the user </script>

您可以反过来这样做

<% name = @user.name %> <script> var name = "John"; <% name %> = name; </script> <% @user.name = name %> <%= name %> <!-- prints the name of the user, in this case "John" -->

显然这不起作用,但出于举例的目的

Obviously this doesn't work, but for the purpose of an example

重点是,您能否将javascript变量的值传递给rails中的ruby变量

The point is, can you pass the value of a javascript variable to a ruby variable in rails

推荐答案

不,你不能直接从javascript传递变量到rails:

No you can't pass a variable directly from javascript to rails:

  • Ruby on Rails '代码在服务器端上执行,以生成页面(包含HTML,CSS和Javascript)。
  • Javascript 的代码在浏览器的客户端上执行。
  • Ruby on Rails' code is executed on the server-side, to generate the page (with HTML, CSS and Javascript).
  • Javascript's code is executed on the client-side, by the browser.

唯一的方法与客户端通信 - >服务器是使用请求。您可以使用AJAX (异步Javascript和XML)从客户端向服务器发送请求,而无需重新加载页面。

The only way to communicate client -> server is to use a request. You can use AJAX (Asynchronous Javascript And XML) to send a request from the client to the server without reloading the page.

您必须了解有关服务器/客户端代码的一些概念。 从网站显示页面的过程:

You have to understand some concepts about code on the server/client side. The process of "displaying a page from a website":

  • (客户端 -side)用户发送向服务器发送页面的HTTP请求,发送页面位置,例如: myapp/users
  • (服务器 -side)服务器获取请求,按照定义的路径找到正确的控制器/操作
  • (服务器 - side)服务器生成HTML / CSS / Javascript页面以发回给用户。它通过视图和& ;;生成HTML。 partials,执行这些页面的ruby代码。
  • (服务器 -side)一旦页面呈现(完全生成HTML / CSS / Javascript),服务器发送HTTP响应
  • (客户端 -side)客户端的浏览器接收服务器的响应,由HTML / CSS / javascript(主要是)组成。浏览器呈现HTML / CSS,并执行javascript。
  • (Client-side) The user sends a HTTP request to the server for a page, sending the location of the page, example: myapp/users
  • (Server-side) The server gets the request, find the proper controller/action following the defined routes
  • (Server-side) The server generates the page in HTML/CSS/Javascript to send back to the user. It generates the HTML via the views & partials, executes the ruby code of these pages.
  • (Server-side) Once the page is rendered (HTML/CSS/Javascript fully generated), the server sends the HTTP response
  • (Client-side) The client's browser receive the response of the server, composed of HTML/CSS/javascript (mostly). The browser renders the HTML/CSS, and execute the javascript.

更多推荐

将变量从Javascript传递到Ruby on Rails

本文发布于:2023-11-24 22:06:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Javascript   Rails   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!