【问题标题】:How to respond with format.pdf in rails 5如何在 rails 5 中使用 format.pdf 响应
【发布时间】:2017-05-05 13:54:40
【问题描述】:

我正在尝试使用 jquery 来获取显示 pdf 页面的控制器操作。在使用 javascript 方式之前,rails 方式有效:

Show.html.erb

<%= link_to "Get PDF", client_path(@client.id, format: :pdf) %>

问题是,我需要一些从 javascript 中获得的参数,因此解决方法是使用 ajax 发出请求:

js:

$.ajax({
  url: "/clients/" + clientId + ".pdf",
  type: 'POST', // Ive also tried GET and created a post route in routes.rb
  data: { //...
  },
  success: function(data, xhr) {
    //...
    console.log('Success.....');
  },
  error: function() {
    console.log("Error....")
  }

});

控制器:

respond_to :html, :xml, :json

def show
   respond_with do |format|
      format.pdf do
        render pdf: "demopdf",
               template: "clients/show.pdf.html.erb",
               locals: {:client => @client}
      end
    end
end

如果我点击我的 rails 按钮,我会看到 pdf 视图,但使用带有按钮点击功能的普通按钮则不会。如何用ajax做到这一点?我得到了成功日志,仅此而已。

编辑:

如何将Bar 发送到我的控制器?我需要在我的 pdf 中包含 Bar?

show.html.erb:

<p id="foo"></p>

js:

$("#foo").text("Bar");

所以基本上我需要传入一些参数:

<%= link_to "Get PDF", client_path(@client.id, format: :pdf) %>

【问题讨论】:

  • 按钮点击需要传递什么参数?
  • 我的文本很少用 javascript 填充,即:&lt;h1 id="foo"&gt;&lt;/h1&gt; 和 js:$("#foo").text("Bar"); 所以我还需要将 Bar 传递给控制器​​,所以我认为 ajax 是最好的?
  • 您是否尝试将远程添加到link_to,应该可以。例如:&lt;%= link_to "Get PDF", client_path(@client.id, format: :pdf, remote: true) %&gt;

标签: javascript ruby-on-rails ruby ajax wicked-pdf


【解决方案1】:

如果您需要发送参数,可以通过在路由代码中添加参数来实现。

&lt;%= link_to "Get PDF", client_path(@client.id, format: :pdf, params1: 'some param', params2: 'other param2' ...) %&gt;

如果您需要使用 ajax 链接,请添加 remote: true 也在那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2018-05-25
    相关资源
    最近更新 更多