Jquery 通过ajax将HTML属性传递给后端ruby
我使用Sinatra在HTML中动态创建按钮,在任何给定的运行时,哈希中的每个键都有一个按钮。由于哈希大小的变化,可能会有更多或更少的按钮。当我单击一个按钮时,我想将与该键相关的值传递回我的Ruby后端 我的Ruby代码是Jquery 通过ajax将HTML属性传递给后端ruby,jquery,html,ruby,ajax,sinatra,Jquery,Html,Ruby,Ajax,Sinatra,我使用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'
#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>
如何将此name属性正确地传递到后端方法?您应该能够使用
params[:link]
或params['link']
从get到POST更改数据类型值
(document).ready(() => {
$('.trial-version').on('click', () => {
$.ajax({
type: "POST",
url: '/run_feature',
dataType: "script",
data: {HashValue: this.attr("name")}
});
});
});
然后将函数名从
获取“/run\u功能”do
到
发布“run_feature”do您的意思是
runFeature(参数['link'])
?什么是runFeature
什么是HashValue
?你真的试过什么吗?如果是,什么?你看了ajax请求实际提交到的url了吗?嗨,链接应该改为HashValue,runFeature是一个ruby函数,我认为它并不重要,我是web开发新手,所以我不确定解决这个问题的最佳方法,我尝试使用类似于我在散列中传递的方式的全局变量,但它们不是特定于按钮的。
(document).ready(() => {
$('.trial-version').on('click', () => {
$.ajax({
type: "POST",
url: '/run_feature',
dataType: "script",
data: {HashValue: this.attr("name")}
});
});
});