如何在Ruby中访问JavaScript变量[重复]

时间:2022-03-06 04:32:23

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to do something very simple, but I can't figure out. How can I access a local JavaScript variable in Ruby? Or, if that's not possible, can I find an element on the page by its name or id? I'm trying to fit it into the following:

我正在尝试做一些非常简单的事情,但我无法弄明白。如何在Ruby中访问本地JavaScript变量?或者,如果那不可能,我可以在页面上找到其名称或ID的元素吗?我正在尝试将其纳入以下内容:

inp = document.getElementById("email").value; 

<% if User.pluck(:email).include? **JAVASCRIPT VARIABLE "INP"** then %>
alert("found")
<% end %>

Thanks.

1 个解决方案

#1


0  

I don't think its possible as Ruby is executed server side and javascript is client side language. But you can use ajax to pass client side variable(JS) to server and tackle this situation.

我不认为它可能因为Ruby是服务器端执行而javascript是客户端语言。但是您可以使用ajax将客户端变量(JS)传递给服务器并解决这种情况。

For Example - using little JS you can pass client side variable to server side and get the result.

例如 - 使用小JS,您可以将客户端变量传递给服务器端并获取结果。

var email = $('#email').val();
$.post('/email_lookup?email='+email,function(data){
  console.log(data);
});

In Controller, you can define an action which will look for provided email and return a json data whether the email exists or not.

在Controller中,您可以定义一个操作,该操作将查找提供的电子邮件并返回json数据,无论电子邮件是否存在。

def email_lookup
  @user = User.where(email: params[:email]).try(:first)
  render json: {
    email_found: @user.present?
  }
end

#1


0  

I don't think its possible as Ruby is executed server side and javascript is client side language. But you can use ajax to pass client side variable(JS) to server and tackle this situation.

我不认为它可能因为Ruby是服务器端执行而javascript是客户端语言。但是您可以使用ajax将客户端变量(JS)传递给服务器并解决这种情况。

For Example - using little JS you can pass client side variable to server side and get the result.

例如 - 使用小JS,您可以将客户端变量传递给服务器端并获取结果。

var email = $('#email').val();
$.post('/email_lookup?email='+email,function(data){
  console.log(data);
});

In Controller, you can define an action which will look for provided email and return a json data whether the email exists or not.

在Controller中,您可以定义一个操作,该操作将查找提供的电子邮件并返回json数据,无论电子邮件是否存在。

def email_lookup
  @user = User.where(email: params[:email]).try(:first)
  render json: {
    email_found: @user.present?
  }
end