将javascript变量分配给ruby变量

时间:2022-08-27 17:42:27

I have a score counter and I'm trying to assign the value of that score counter to a ruby variable, and then have that variable be saved.

我有一个分数计数器,我试图将该分数计数器的值分配给ruby变量,然后保存该变量。

View:

        var score = 0;
        window.setInterval(
        function countscore() {
            if($('#game-area').is(':animated')){
                score = score + 1;
                document.getElementById("score").innerHTML = score;
                document.getElementById("score").submit(); //trying to assign here
            }

        }, 100); 

controller:

def index
    @user = User.find(current_user)     
    @score = @user.score
end

2 个解决方案

#1


1  

You will need to do something more complicated than that. The ERB code generates an HTML file that gets sent to the client, which has no idea what server software is sending it the HTML file, so it can't assign a server-side variable. You have to upload the value to the server in some way. For example, you could use a form submission, URL querystring parameters, or an AJAX request.

你需要做一些比这更复杂的事情。 ERB代码生成一个HTML文件,该文件被发送到客户端,该文件不知道哪个服务器软件正在向HTML文件发送它,因此它无法分配服务器端变量。您必须以某种方式将值上传到服务器。例如,您可以使用表单提交,URL查询字符串参数或AJAX请求。

#2


-1  

Try the following code:

请尝试以下代码:

var score = '<%= @user.score %>'

#1


1  

You will need to do something more complicated than that. The ERB code generates an HTML file that gets sent to the client, which has no idea what server software is sending it the HTML file, so it can't assign a server-side variable. You have to upload the value to the server in some way. For example, you could use a form submission, URL querystring parameters, or an AJAX request.

你需要做一些比这更复杂的事情。 ERB代码生成一个HTML文件,该文件被发送到客户端,该文件不知道哪个服务器软件正在向HTML文件发送它,因此它无法分配服务器端变量。您必须以某种方式将值上传到服务器。例如,您可以使用表单提交,URL查询字符串参数或AJAX请求。

#2


-1  

Try the following code:

请尝试以下代码:

var score = '<%= @user.score %>'