javascript 将多个rails变量传递给javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8263951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:50:20  来源:igfitidea点击:

Passing multiple rails variables to javascript

javascriptruby-on-railsruby-on-rails-3ruby-on-rails-3.1rjs

提问by alik

I have some values in ruby (variables and objects / hash) that I want to pass on to javascript on the rendered page. Currently I use these methods to simply write the javascript of declaring the variables at the client end.

我在 ruby​​ 中有一些值(变量和对象/哈希),我想将它们传递给渲染页面上的 javascript。目前我使用这些方法来简单地编写在客户端声明变量的javascript。

  def declare_as_js_vars vars
    string = ""
    vars.each do |name, value|
      string += self.declare_as_js_var(name, value)
    end
    string
  end

  def declare_as_js_var name, value
    name.to_s + "='" + value.to_s + "';"
  end

The problem here is that I am unable to declare objects, and have to declare vars individually. I was wondering if there is some way in rails to easily do this because this is turning out to be quite a hack.

这里的问题是我无法声明对象,必须单独声明变量。我想知道 Rails 是否有某种方法可以轻松做到这一点,因为结果证明这是一个相当大的黑客。

How should I pass variables and objects to javascript? Please provide some syntax example

我应该如何将变量和对象传递给 javascript?请提供一些语法示例

回答by Jaro

It' s a bit late but maybe it will help the others. There is a nice gem called gonwhich is very useful with passing variables from rails to javascript. You can also send the whole object.

有点晚了,但也许它会帮助其他人。有一个很好的 gem 叫做gon,它对于将变量从 rails 传递到 javascript 非常有用。您也可以发送整个对象。

In the controller you can have something like this

在控制器中你可以有这样的东西

@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}
gon.your_int = @your_int
gon.your_other_int = 345 + gon.your_int
gon.your_array = @your_array
gon.your_array << gon.your_int
gon.your_hash = @your_hash
gon.your_object = Table.find(params[:id])

then in the javascript it will be available like

然后在javascript中它将像

alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)
alert(gon.your_object.name)

There is also a railscastabout it.

还有一个关于它的railscast

回答by bloudermilk

I like to use script tags of type JSON to get the job done. It avoids polluting the global namespace and Rails happens to have great support for serializing objects to JSON.

我喜欢使用 JSON 类型的脚本标签来完成工作。它避免了对全局命名空间的污染,而且 Rails 对将对象序列化为 JSON 有很大的支持。

You might use something like this in you view:

你可能会在你的视图中使用这样的东西:

<script id="my_vars_json" type="text/json">
    <%= @my_vars.to_json %>
</script>

Then it's up to you to parse the JSON with JavaScript. I like to use jQuery:

然后由您来使用 JavaScript 解析 JSON。我喜欢使用 jQuery:

$(function () {

    var myVarsJSON = $("#my_vars_json").html(),
        myVars     = $.parseJSON(myVarsJSON);

    console.log(myVars);

});

Hope that helps!

希望有帮助!

回答by Reza

I needed to get user's first name from database and pass the value to a javascript variable in JSON format.

我需要从数据库中获取用户的名字并将值传递给 JSON 格式的 javascript 变量。

I then declared a rubyvariable named token which takes idand firstnameattribute from the user table,

然后我声明了一个ruby名为 token的变量,它从用户表中获取idfirstname属性,

  ActiveRecord::Base.include_root_in_json = false

  @token = User.all.to_json(only: [:id, :firstname])

In the erbfile, I used the following line,

erb文件中,我使用了以下行,

var tokenList = <%= @token.html_safe %>

回答by mrded

I think using Gon gemwill be the best solution. also check out this video casts

我认为使用Gon gem将是最好的解决方案。也看看这个视频演员

回答by MQuy

i found that gem client variable, it look promising. your configuration and variable are pass to client and you can easy get or set in client

我发现 gem客户端变量,它看起来很有希望。您的配置和变量传递给客户端,您可以在客户端轻松获取或设置

回答by BvuRVKyUVlViVIc7

Maybe you should try to work with objects.to_json ;)

也许你应该尝试使用 objects.to_json ;)

回答by ahnbizcad

Take a look at this.

看看这个。

http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs

http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs

One of the easiest ways is to use js.erb file, where you can do ruby tags to access variables that you defined in the controller action.

最简单的方法之一是使用 js.erb 文件,您可以在其中执行 ruby​​ 标记来访问您在控制器操作中定义的变量。

You need to use a respond_to block in the controller action, specifying the action to be able to respond to javascript.

您需要在控制器操作中使用 respond_to 块,指定能够响应 javascript 的操作。

items_controller.rb

items_controller.rb

class ItemsController < ApplicationController

  def action
    respond_to do |format|
      format.js
      #format.html {}    #  These are for allowing other types of formats to be responded to.
      #format.json {}    #  But they are not necessary for using this js.erb way of doing things.
    end
  end

end

/views/items/action.js.erb

/views/items/action.js.erb

$(div).html('The cat has erased your page');