Passing variable from Javascript to Ruby on Rails

前端 未结 1 1052
时光取名叫无心
时光取名叫无心 2020-12-19 13:50

In rails you can do this:

<% name = @user.name %>


        
相关标签:
1条回答
  • 2020-12-19 14:25

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

    • 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.

    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 vs client side. The process of "displaying a page from a website":

    • (Client-side) The user sends an 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, the server sends the HTTP response with the HTML/CSS/Javascript in the body.
    • (Client-side) The client's browser receives the response of the server and reads the body composed of HTML/CSS/Javascript (mostly). The browser parses and renders the HTML/CSS, and execute the javascript.
    0 讨论(0)
提交回复
热议问题