2011-12-14 81 views
0

如何從JavaScript執行PUT,POST或DELETE調用?Rails javascript數據庫查詢

我已經收集了一些數據使用jQuery的拖放。那麼我怎麼把它發送到數據庫?我想我可以使用jQuery.ajax,但無法解決問題。

任何指針讚賞。

解決方案:

這是工作

$(document).ready(function() { 
    $.ajax({ 
     type: "PUT", 
     url: "/articles/8", // should be mapped in routes.rb 
     data: {articles:{name:"New Name"}} 
     }); 
}); 

JavaScript,但它不會改變第8條新名稱的名稱。 Firebug顯示沒有錯誤,但我仍然無法將數據傳遞給編輯。

該URL是使用put url的標準更新,它存在於路由中。

回答

2

您可以使用jQuery ajax:這是一個非常好的方式來動態處理瀏覽器請求與服務器端代碼。

jQuery('#element_id').on('click change',function(){ // use event as per your need 
     $.ajax({ 
       type: "GET", 
       url: "/edit_comment", // should be mapped in routes.rb 
       data: {comment:"new comment"}, 
       datatype:"html", // check more option 
       success: function(data) { 
         // handle response data 
         }, 
       async: true 
      });  

}); 

有關詳情,請點擊以下鏈接:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/category/ajax/

Rails代碼

def edit_comment 
@comment = params[:comment] 
// store to database 
    response_to do |format| 
    render :html 'comment.html' 
    end 
end 

routes.r b

map.edit_comment "edit_comment", :controller => 'comment', :action => 'edit_comment' 
+0

感謝您的幫助 - 我需要多一點澄清! 如果我想用它來編輯評論,我可以使用@comment來找到控制方法的URL? 當我輸入數據時,如果我想要編輯名稱是愛德華它是 data:{name:「Edward」} – Edward 2011-12-14 11:19:46

+0

是的,你可以做到這一點.. – 2011-12-14 12:02:25

2

對於PUT和DELETE添加一個額外的參數名爲_method:_method=PUT
Rails使用它來模擬PUT和DELETE。