问题
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