【问题标题】:Pass HTML attribute through ajax to backend ruby通过 ajax 将 HTML 属性传递给后端 ruby
【发布时间】: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


【解决方案1】:

您应该能够使用 params[:link]params['link'] 从 ajax 访问传递的数据

【讨论】:

    【解决方案2】:

    您应该将数据类型值从​​ GET 更改为 POST

      (document).ready(() => {
      $('.trial-version').on('click', () => {
            $.ajax({
                        type: "POST",
                        url: '/run_feature',
                        dataType: "script",
                        data: {HashValue: this.attr("name")}
            });
         });
    });
    

    然后将函数名从 得到'/run_feature'做 到 发布“run_feature”做

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 2021-01-19
      • 2010-11-04
      • 1970-01-01
      • 2011-09-20
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      相关资源
      最近更新 更多