简体   繁体   English

将JavaScript变量发送到Rails助手方法

[英]Send javascript variable to rails helper method

I have an array of video names, I want to grab a random video name from this array. 我有一个视频名称数组,我想从该数组中获取一个随机的视频名称。 But when I call a helper method to do all this, I get the same random number, and random video each time. 但是,当我调用一个辅助方法来完成所有这些操作时,我会得到相同的随机数,并且每次都会获得随机视频。

I believe this is because the helper method is only called once even though I'm trying to "call it" multiple times, it's just the results of that method that are "called" multiple times. 我相信这是因为即使我试图多次“调用”该辅助方法也仅被调用一次,而只是多次“调用”该方法的结果。

So what I'm thinking is to find a way to send a JavaScript variable to the helper method, but I have no idea (nor does Google) of how best to do this. 因此,我的想法是找到一种将JavaScript变量发送到helper方法的方法,但是我不知道(谷歌也不知道)如何最好地做到这一点。

To keep it simple, with just trying to obtain a new random number each time: 为简单起见,每次尝试获取一个新的随机数:

JS: JS:

function randomNumber() {
    alert("<%= random_number %>");
}

setTimeout(function(){
    randomNumber();
}, 2000);

html.erb: html.erb:

helper_method :random_number
def random_number
  rand(0..10)
end

The same random number is shown each time. 每次显示相同的随机数。

Requests 要求

Rails works on "requests" Rails处理“请求”

Because Rails is server-side, it works with these requests to "render" the pages / views you see on your screen. 因为Rails是服务器端的,所以它可以处理这些请求,以“呈现”您在屏幕上看到的页面/视图。 Each request is treated individually, meaning that you have to pass it everything the server will need to render the correct view for you 每个请求都被单独对待,这意味着您必须将服务器为您呈现正确视图所需的所有内容传递给它

The problem you're alluding to is you're trying to use data which has already been rendered. 您提到的问题是您尝试使用已经渲染的数据。 The "helper" view was rendered when you sent the HTTP request to Rails, and consequently is going to use the same data over and over 当您将HTTP请求发送到Rails时,呈现了“ helper”视图,因此将一遍又一遍地使用相同的数据


Client-Side Vs Server-Side 客户端与服务器端

The problems you're seeing come from the difference between client-side (JS) and server-side (Rails). 您看到的问题来自client-side (JS)和server-side (Rails)之间的差异。 The difference is that you can't access Rails from JS, unless you send a "request" (probably via ajax ) 区别在于,除非您发送“请求”(可能通过ajax ),否则您无法从JS访问Rails。

In order to trigger Rails from the client-side, you have to send a request. 为了从客户端触发Rails,您必须发送一个请求。 That's either done with a browser click, or Ajax 通过浏览器点击或Ajax完成


Your Question 你的问题

You're trying to load a random number between 1 & 10 from Rails 您正在尝试从Rails加载1到10之间的随机数

This can be handled entirely by JS if you use the right functions / code 如果您使用正确的函数/代码,则可以完全由JS处理

Alternatively, you can use Ajax to request the helper from Rails, but this is highly inefficient, as it will send an unnecessary request to the server 另外,您可以使用Ajax向Rails请求帮助程序,但这效率很低,因为它将不必要的请求发送到服务器。

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

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