简体   繁体   English

如何从Ruby变量在Javascript中存储在localStorage中

[英]How to store in localStorage in Javascript from Ruby variable

I try to store a token in my localstorage from a ruby variable, As I understood, you can only set LocalStorage with Javascript, So here is my question, how can I pass my variable from Ruby to Javascript ?我尝试从 ruby​​ 变量将令牌存储在我的 localstorage 中,据我所知,您只能使用 Javascript 设置 LocalStorage,所以这是我的问题,如何将我的变量从 Ruby 传递给 Javascript? I saw some answers with script tag in the view, but is there any solution to do it directly in the app.js folder ?我在视图中看到了一些带有 script 标签的答案,但是有什么解决方案可以直接在 app.js 文件夹中完成吗?

So here is my Controller :所以这是我的控制器:

 @token = HTTParty.post('https://test.pro/2.0/auth/token/access', 
      body: {
          client_id: XXX,
          client_secret: "YYYYYYYYYYYYYY",
          code: LLLLLL
      }
  )

And in my view if I do a <%= @token %>, I have the following result :在我看来,如果我执行 <%= @token %>,我会得到以下结果:

{"access_token": "1VwCAjhsfCsdEoBoQs1G9kLHKoWOcJjamyj1s8_NQPrHeGNagzYYFrXKp_VlY", "token_type": "Bearer"}

Thanks for your help !谢谢你的帮助 !

If you want to perform javascript from within a ruby file you can use a javascript_tag:如果您想从 ruby​​ 文件中执行 javascript,您可以使用 javascript_tag:

https://apidock.com/rails/ActionView/Helpers/JavaScriptHelper/javascript_tag https://apidock.com/rails/ActionView/Helpers/JavaScriptHelper/javascript_tag

An example of how to use it:如何使用它的示例:

Accessing Ruby objects in javascript 在 JavaScript 中访问 Ruby 对象

In your case, something in your view like:在您的情况下,您认为以下内容如下:

<% javascript_tag do %>
   localStorage.setItem('accessToken', <%= @token["access_token"] %>);
   localStorage.setItem('tokenType', <%= @token["access_token"] %>);
<% end %>

Should do the trick应该做的伎俩

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM