2015-09-28 43 views
0

當涉及到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記錄)。

+0

你有一個異常和堆棧跟蹤,你可以分享?檢查您的rails控制檯和/或development.log文件。 format.js和format.json有什麼區別?除非你有格式的視圖模板。JS,我建議從你的respond_to塊中刪除它。 –

+0

我對LineItem是一個連接表的種類有點困惑,但是您將項目的id作爲主鍵傳遞,並假設它們始終具有相同的ID。在查詢LineItem時不應該使用另一個字段? –

+0

@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

回答

0

我想你只需要在表單定義更改路線名稱是這樣的:

= form_for :line_item, url: line_item_path(@product.id), remote: true do |f| 

此外,如果您可以設置sellprice作爲更新方法的一部分,這將是可取的,而不是有一個額外的控制器方法。

+0

這是我現在在我的標題中收到的: '遠程地址:127.0.0.1:9292 請求URL:http:// localhost:9292/line_items.6 請求方法:POST 狀態碼:404 Not Found' – mohnstrudel

0

我認爲你有兩個問題。首先,正如Ben指出的那樣,你的網址是錯誤的。它需要像/line_items/5。如果您將您的form_for中的line_items_path(product_id: @product.id)更改爲line_items_path(@product),則應該會生成正確的網址。

你的第二個問題是你基本上做了兩次ajax請求 - 一次是從咖啡腳本中作爲PUT(它應該正確的改變url),一次從form_for中遠程設置爲true。這是form_for正在執行「POST」請求,因爲您沒有在那裏指定方法。

我會建議你的form_for(method: :put)添加put方法(或創建一個POST路由)並刪除做ajax的coffeescript。如果您需要來自瀏覽器的信息以填充sellprice,請將該邏輯留在coffeescript中,但只需更新表單中的字段值(隱藏或以其他方式),並將其作爲表單的一部分提交。