2015-09-25 28 views
1

我正在做一個小的rails應用程序。遠程真正的button_to不讓阿賈克斯呼籲

我正在嘗試做一個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 . 
+0

你可以擺脫'method' - post是一個默認值。 – BroiSatse

+1

值得添加您的application.js,因爲這似乎是問題的原因。 – Shadwell

+0

檢查這看起來重複http://stackoverflow.com/questions/19710040/ajax-call-when-clicking-on-a-button-in-rails – Arvind

回答

2

問題通常是因爲你沒有正確加載jQuery的。 button_to ... remote: true成爲ajax調用,因爲remote: true觸發JavaScript,該按鈕會改變按鈕的行爲。

在你application.js你需要JavaScript和:

= require jquery 
= require jquery_ujs 

這應該是:

//= require jquery 
//= require jquery_ujs 

有了正確加載,你應該得到的按鈕表現爲預期的jQuery。

+0

謝謝@Shadwell!你是對的。爲什麼要求jquery錯誤? –

+1

要求它是它被要求的方式並沒有錯。這些線路確實需要「註釋掉」的格式,因爲這是資產管道所期望的。 (我不認爲你需要'/ = require jquery',因爲'jquery_ujs'包含它。 – Shadwell