Rails javascript database queries

两盒软妹~` 提交于 2019-12-05 10:43:25

问题


How do I do a PUT, POST or DELETE call from javascript?

I've collected some data using jquery drag and drop. How do I then send this to the database? I think I might be able to use jQuery.ajax but can't work out how exactly.

Any pointers appreciated.

Solution:

This is the javascript that works

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

But it doesn't change the name of article 8 to New Name. Firebug shows no errors, but I still can't pass data to the edit.

The url is the standard update using put url, it exists in the routes.


回答1:


You can use jQuery ajax for this: It is a very good way to handle browser requests dynamically with server side code.

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
            });    

});

For more details check these links:

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

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

RAILs code:

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

routes.rb

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



回答2:


For PUT and DELETE add an extra parameter named _method: _method=PUT
Rails uses it to simulate PUT and DELETE.



来源:https://stackoverflow.com/questions/8503174/rails-javascript-database-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!