将变量从Javascript传递到Ruby on Rails [英] Passing variable from Javascript to Ruby on Rails

查看:302
本文介绍了将变量从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请求,发送页面位置,例如: http://myapp.com/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: http://myapp.com/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆