将变量从 Ruby 传递给 JavaScript

passing variables form ruby to javascript

本文关键字:JavaScript Ruby 变量      更新时间:2023-09-26

我正在尝试从搜索提示中选择用户的值并将其传递给javascript。在我的搜索控制器中,它存储在@result中。然后我找到了我需要的东西(参数[:query_id]

希望通过将未签名用户的选择添加到提示中来使未签名用户的提示更花哨一些。尝试了一个简单的方法——

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

但是收到此错误消息: 引用错误:找不到变量:getElementById

尝试从 ruby 数组中获取此变量:

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

但它返回空

添加 searh 控制器的代码,如建议:

定义索引 respond_to do |format| 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

然后在搜索 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不是在全局对象中定义的。它是document的属性。

尝试:

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

Rails附带了jQuery,为什么不使用它呢?

我想这就是你想要的。

$('query').val()

但是您应该跳转到浏览器中呈现的 html 以检查是否要选择作为名称查询的节点(我认为这是 rails 所做的或您认为的 id 查询