當涉及到AJAX請求時,我正在使用URL參數掙扎。我基本上想要做的是 - 我的頁面上有一個小計算器(這是一家商店),結果顯示在div #priceValue中。我想通過Ajax將該值傳遞給我的記錄。Rails應用程序 - 通過ajax請求傳遞值來記錄
因此,這裏是我的看法:
=form_for :line_item, url: line_items_path(product_id: @product.id), remote: true do |f|
...some fields and calculator goes in there...
=button_tag(type: 'submit', id: 'add_item_to_cart', class: 'btn btn-primary shopping-cart-btn') do
%i.fa.fa-shopping-cart
Buy
了LineItem有幾分加盟模式,因爲他們持有的信息對車,對項目所屬的,在原有產品(它的id)和金額。我想將一個:sellprice價值(客戶的最終購買價格)傳遞給lineitems記錄。
自從我加入到產品展示#控制器購物車內的商品,我嘗試過編輯products.coffee進行Ajax調用:
$(document).ready ->
$('div.box form').submit (event) ->
url = $(this).attr('action')
sellprice = parseInt($('#priceValue').text(), 10)
# console.log(url) <- this works
# console.log(sellprice) <- this works
$.ajax
type: 'PUT'
url: url
data: { line_item: { sellprice: sellprice } }
dataType: 'json'
success: (json) ->
console.log('success')
但在這裏我收到PUT http://localhost:9292/line_items?product_id=5 404 (Not Found)
錯誤。 這是我的網絡選項卡顯示 - http://take.ms/s4zie
我試圖按照codeschool 5級指導,甚至寫了自定義的方法:
def sellprice
@line_item = LineItem.find(params[:id])
@line_item.sellprice = params[:line_item][:sellprice]
@line_item.save
respond_to do |format|
format.js
format.json { render json: @line_item.to_json(only: :sellprice) }
end
end
並取得該路線:
resources :line_items do
put :sellprice, on: :member
end
在標題中,我甚至可以看到所需的值:
Query String Parameters
product_id:5
Form Data
line_item[sellprice]:880
但我無法讓它工作...請不要對我苛刻,我肯定缺少一些基本的東西,但阿賈克斯的東西對我來說是一個全新的世界(另一方面,不知道如何將JS值傳遞給Rails記錄)。
你有一個異常和堆棧跟蹤,你可以分享?檢查您的rails控制檯和/或development.log文件。 format.js和format.json有什麼區別?除非你有格式的視圖模板。JS,我建議從你的respond_to塊中刪除它。 –
我對LineItem是一個連接表的種類有點困惑,但是您將項目的id作爲主鍵傳遞,並假設它們始終具有相同的ID。在查詢LineItem時不應該使用另一個字段? –
@SeanHuber這是我的瀏覽器控制檯顯示的內容:'PUT http:// localhost:9292/line_items?product_id = 5 404(Not Found)' 我的錯誤建議如下 - 因爲我的表單是換一個新行項目(因爲每次客戶添加一些東西到他的購物車中都會創建一個新的訂單項),我試着同時更新它。因此,該網址用於創建新記錄,但我正在嘗試PUT-動詞。如果我將動詞更改爲POST,瀏覽器控制檯會提供以下信息:'POST http:// localhost:9292/line_items?product_id = 7 500(內部服務器錯誤)' – mohnstrudel