javascript - 将 ruby​​ 变量从 Controller 分配给 javascript 变量

标签 javascript ruby-on-rails variables

我到处寻找并尝试了我能找到的所有建议,但它仍然不起作用。基本上我试图将输入的任何内容分成单独的单词,然后使每个单词成为一个链接。我试图从数据库中获取一个值并将其传递给 javascript,以便我可以在 javascript 中使用一个变量作为该值。这是代码:

在 Controller 中:

def show
  @icelandic_reader = IcelandicReader.find(params[:id])
  @icelandic_reader_json = @icelandic_reader.text.to_json;

respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @icelandic_reader }
 end
end

在 .js.erb 文件中:

window.onload = function() {
  var myText = <%= @icelandic_reader_json %>;
  console.log("test1");
  var words = myText.split(" ");
  console.log("test2");
  var numWords = words.length;
  var textToInsert;

  for (var i = 0; i < numWords; i++) {
      console.log("inside for loop");
      textToInsert += "<a href=#>" + words[i] + "</a>" + " ";
  }

  document.getElementById('icelandic_reader_text').innerHTML = textToInsert;

}

我没有收到任何错误,但我没有看到任何测试控制台日志出现。我已经尝试了所有找到如何分配 ruby​​ 变量的方法,但它不起作用。我有 ruby 3.2.6。谢谢!

最佳答案

这对我来说看起来很奇怪。如果 @icelandic_reader.text 只是一个字符串,为什么要调用 to_json 呢?如果它是 @icelandic_reader 的属性,您可以从 View 访问它,那么为什么还要将它分配为实例变量呢?为什么还需要 render json 调用? Rails 只会在您的 View 文件夹中查找 show.js.erb

试试这个:

# controller

def show
  @icelandic_reader = IcelandicReader.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.json 
  end
end

在你的 js.erb 中:

# js.erb

var myText = "<%= @icelandic_reader.text %>";

关于javascript - 将 ruby​​ 变量从 Controller 分配给 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676636/

相关文章:

javascript - 服务器上网站不同页面之间的导航

ruby-on-rails - FactoryGirl : Creating dynamic factories with parameters?

javascript - 如何将字符串变成变量

c++ - 为什么会出现切片?

javascript - 为什么我的页面上的事件选项卡没有变化?

javascript - 如何在具有相同类的多个文本框上将 readonly 属性设置为 false?

javascript - JQuery Mobile自定义Flipbox设置初始化值

javascript - 在 rails 3.2.2 中使用 $.ajax() 异步获取数据

ruby-on-rails - 在 rails 配置文件和 javascript 之间共享变量

variables - 如何在 julia 中将变量类型 "SentinelArrays"转换为 "Arrays{Float64,n}"