如何使用 sinatra 和 bootstrap 从 ruby 更改 html 元素

How can I change an html element from ruby using sinatra and bootstrap

这是我的 index.erb 文件:

  <a class="btn" href='javascript:TestFunction()' role="button">TestFunction</a>

  <script language="javascript"> 

     function TestFunction() {
       $.post("test_function", { action: "foo", name: "bar" } );
     }

  </script>
</body>

我的 app.rb 文件看起来像这样

class ConfigureApp < Sinatra::Base
  get '/' do
    erb :index
  end

  post '/test_function' do
    button_action = params.fetch("action")
    test_class = TestClass.new
    test_class.action(button_action)
  end
end

TestClass.rb 文件:

class TestClass
  def action(button_action)
    if button_action == "foo"
      new_button_label = "something else"
    end
  end
end

有没有办法让我从 TestClass 更改 TestFunction 按钮的标签?所以使用我上面的例子,我可以重命名 TestFunction 按钮,"something else"?

我想出了一个办法。我可以发送 post '/test_function' 并发送操作和名称参数。然后用一个函数作为post函数的第三个参数,从Ruby这边得到一个return,可以return按钮的新标签。然后我可以使用 Jquery 来更新按钮的 html 或 innerText 或任何我需要更新的内容。我是这样实现的:

  <a class="btn" id='btn-foo' href='javascript:TestFunction()' role="button">TestFunction</a>

  <script language="javascript"> 

     function TestFunction() {
       $.post("test_function", { action: "foo", name: "bar" }, function(data) {
         $('#btn-foo').html = data;
       });
     }

  </script>
</body>