【发布时间】:2018-11-16 05:46:34
【问题描述】:
我正在使用 Sinatra 在 HTML 中动态创建按钮,在任何给定的运行时,哈希中的每个键都有一个按钮,由于哈希大小的变化,可能会有更多或更少的按钮。当我单击一个按钮时,我想将与该键关联的值传递回我的 Ruby 后端。
我的 Ruby 代码是
#app.rb
require 'sinatra'
require 'net/http'
require_relative './hashmaker.rb'
enable :sessions
set :views, "views"
set :bind, '0.0.0.0'
get '/' do
@hash = hashmaker.make_crazy_changing_hash(from_a_directory_of_files)
erb: index
end
get "/run_feature" do
return runFeature(HashValue)
我用 HTML 制作了一个表格,每个哈希键都有一个按钮
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"> .
</script>
<script src="ajax.js"></script>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div style="overflow-x:auto;">
<table>
<% @hash.keys.each do |feat| %>
<tr>
<td><%= feat %></td>
<% @hash[feat].each do |elem| %>
<td>
<button class="trial-version" name=<%= elem[1] %>><%= elem[0] %></button>
</td>
<% end %>
</tr>
<% end %>
</table>
</div>
</body>
</html>
我已尝试将哈希值添加为按钮的名称,然后我想通过在我的 jquery onclick 方法中使用 ajax 将该名称传递给 Ruby 后端 /run_feature 获取。
我当前的 ajax 目前看起来像这样:
(document).ready(() => {
$('.trial-version').on('click', () => {
$.ajax({
type: "GET",
url: '/run_feature',
dataType: "script",
data: {HashValue: this.attr("name")}
});
});
});
如何正确地将这个名称属性传递给我的后端方法?
【问题讨论】:
-
你的意思是
runFeature(params['link'])?runFeature是什么HashValue是什么?你真的尝试过什么吗?如果是这样呢?有没有看 ajax 请求实际提交到的 url? -
嗨,应该将链接更改为 HashValue 并且 runFeature 是一个我认为不重要的 ruby 函数,我是 Web 开发新手,所以我不确定解决问题的最佳方法,我尝试使用类似于我传入哈希的方式的全局变量,但它们不是特定于按钮的。
标签: jquery html ruby ajax sinatra