简体   繁体   English

将变量从ruby传递到javascript

[英]passing variables form ruby to javascript

I am trying to get the value user selected from search prompt and pass it to javascript. 我试图从搜索提示中选择值用户,并将其传递给javascript。 in my search controller it's stored in @result. 在我的搜索控制器中,它存储在@result中。 I am then finding what I need with (params[:query_id] 然后,我正在寻找所需的(params [:query_id]

Wanted to make prompt for unsigned users a bit fancier by adding their selection to prompt. 希望通过将未签名的用户的选择添加到提示中来为未签名的用户提供提示。 Tried it a simple way - 尝试了一个简单的方法-

var selected = getElementById('#query').value;

But got this error message: ReferenceError: Can't find variable: getElementById 但是收到了以下错误消息:ReferenceError:找不到变量:getElementById

Tried to get this variable from a ruby array: 试图从红宝石数组获取此变量:

var selected= <%= @result.to_json %>;

But it returns null 但它返回null

Adding searh controller's code, as suggested: 按照建议添加searh控制器的代码:

def index respond_to do |format| def index response_do |格式| format.html {render :text => "html"} format.html {render:text =>“ html”}

  format.js  do
    @search = SearchItem.search{ keywords params["query"] }

    @result = []
    @search.each_hit_with_result do |hit, item|
      @result << {:name => hit.stored(:name), :id => item.id}
    end

    render :json => @result.to_json

  end

end

Then in search html I have 然后在搜索HTML我有

#search
  = form_tag find_from_query_entries_path, :remote => true, :id => "search_form" do
    = text_field_tag :query, nil
    = hidden_field_tag :query_id

getElementById is not defined in global object. 未在全局对象中定义getElementById It is a property of a document . 它是document的属性。

Try: 尝试:

var selected = document.getElementById('#query').value;

Rails comes with jQuery so why not use it? jQuery附带了Rails,为什么不使用它呢?

I think this is what you want. 我想这就是你想要的。

$('query').val()

But you should jump into the rendered html in your browser to check if the node you want to select as the name query (wich I think it's what rails does or id query as you think it is 但是,您应该在浏览器中跳入呈现的html,以检查是否要选择作为名称查询的节点(至于我认为这是Rails所做的,或者是id的查询,因为您认为是)

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

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