【问题标题】:rails link_to with post request and a payload (json object)带有 post 请求和有效负载(json 对象)的 rails link_to
【发布时间】:2019-07-13 04:03:37
【问题描述】:

我想从一个路由(主路由)发送一个 post 请求到另一个带有 link_to 链接和有效负载的路由,以便获取此请求的控制器将访问一个 json 文件(或从 DB 获取的另一个数据)我当前的 rails link_to 代码是:

<%= link_to "{{product}}", controller: 'main', action: 'product', payload: 'msg', method: :post , tabindex:14 %>

传递有效载荷:'msg' 作为 GET 请求参数! 在浏览器路径上看到的是:

http://localhost:3000/product?method=post&payload=msg&tabindex=14

我想做的是在 POST 请求中发送有效负载,而不在屏幕上看到参数。 另一个问题 - 我不想发送“msg”,而是查询我的数据库(例如 Product.find(1))以及我想作为有效负载发送的结果。我以后如何访问这个对象?

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:
# routes.rb
Rails.application.routes.draw do
  get 'users/index'
  post '/post', to: 'users#post'
  root to: 'users#index'  
end
<% # index.html.erb %>
<%= link_to_post 'Post Link', '/post', {foo: :bar, bar: :foo, json: { qux: :baz}.to_json} %>
<% # post.html.erb %>
<h1>Posted</h1>
params.inspect: <%= params.inspect %>
<br />
<br />
<%= link_to 'Go back', '/' %>
# application_helper.rb
module ApplicationHelper
  def link_to_post(body, url, params = {})
    form_tag url do |f|
      params.each do |key, value|
        concat hidden_field_tag(key, value)
      end
      concat link_to(
        body,
        '#',
        onclick: '$(this).closest("form").submit(); return false;'
      )
    end
  end
end
<% # application.html.erb %>
<!DOCTYPE html>
<html>
  <head>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>


或者您可以使用 AJAX 发送 POST 请求

<!DOCTYPE html>
<html>
  <head>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' %>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.0/noty.js' %>
    <%= stylesheet_link_tag 'https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.0/noty.min.css' %>

    <script type="text/javascript">
      $(function() {
        $('.sendAjaxPostRequest').click(function() {
          $.ajax({
            url: "/post",
            method: "POST",
            data: {
              json: $(this).data('json')
            }
          }).done(function() {
            new Noty({
              text: "Data was successfully submitted to server via AJAX",
              type: "success"
            }).show();
          }).fail(function() {
            new Noty({
              text: "Couldn't send data",
              type: "error"
            }).show();
          });
        })
      });      
    </script>
  </head>
  <body>
    <%= link_to 'Send POST request with ajax', '#', class: 'sendAjaxPostRequest', data: { json: { foo: 'bar' }.to_json } %>

    <!-- It will render
    <a class="sendAjaxPostRequest" data-json="{&quot;foo&quot;:&quot;bar&quot;}" href="#">Send POST request with ajax</a>
    -->
  </body>
</html>
Rails.application.routes.draw do
  get 'users/index'
  post '/post', to: 'users#post'
  root to: 'users#index'  
end
class UsersController < ApplicationController
  skip_before_action :verify_authenticity_token

  def post
    Rails.logger.info("params[:json]: #{params[:json]})")
    render json: { status: 'success' }
  end
end

【讨论】:

  • 这是一个有趣的方法!。但是,在我的应用程序中,我们使用 angularJS(遗留项目)和 rails。并且没有表格。只是一个应该从数据库中获取的 json(例如 Product.find(1) ),然后将发布请求发送到路由:/product.
  • 另一种解决方案是使用 ajax 发送 POST 请求。我更新了我的答案并添加了 AJAX 示例。您可以在表单或 AJAX 请求中发送 POST 参数。常规的link_to helper 无法发送 POST 参数。
  • > 我的link_to_post helper 会生成一个隐藏的表单,所以应该没有问题。
猜你喜欢
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2015-05-07
相关资源
最近更新 更多