【问题标题】:remote true on button_to not makes ajax callbutton_to 上的远程 true 不进行 ajax 调用
【发布时间】:2015-09-25 10:53:45
【问题描述】:

我正在做一个小型 Rails 应用程序。

我正在尝试进行 ajax 调用。 尽管我使用remote: true,但 button_to 正在发出非 ajax 请求。它会将我重定向到此网址http://localhost:3000/lines?product_id=1

<% @products.each do |product| %>
  <%= link_to product.name, controller: "store", action: "show", id: product %><br>
  <%= button_to "Add to Cart", {controller: "lines", action: "create", product_id: product.id}, method: "POST", remote: true %>
<% end %>

github repo

有什么想法吗?

谢谢!

---编辑--- 这是我的 application.js

= require jquery
= require jquery_ujs
//= require turbolinks
//= require_tree .

【问题讨论】:

  • 你可以去掉method - post 是默认的。
  • 值得添加您的 application.js,因为这似乎是问题的原因。
  • @Arv - 一些问题,不同的原因。 :) Shadwell 的回答是正确的。 :)

标签: javascript jquery ruby-on-rails ajax button-to


【解决方案1】:

这样的问题通常是因为您没有正确加载 jquery。 button_to ... remote: true 变成了一个 ajax 调用,因为 remote: true 触发了改变按钮行为的 javascript。

在您的 application.js 中,您需要 javascript:

= require jquery
= require jquery_ujs

这应该是:

//= require jquery
//= require jquery_ujs

正确加载 jquery 后,您应该可以让按钮按预期运行。

【讨论】:

  • 感谢@Shadwell!你说的对。为什么要求 jquery 是错误的?
  • 要求它并没有错,它是被要求的方式。这些行确实需要“注释掉”格式,因为这是资产管道所期望的。 (我认为您不需要 //= require jquery,因为 jquery_ujs 包含它。
猜你喜欢
  • 2013-01-07
  • 2013-03-15
  • 1970-01-01
  • 2023-03-30
  • 2011-12-23
  • 1970-01-01
  • 2012-07-01
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多