How do I make AJAX request to actions that require authentication in Rails?
I am trying to send an AJAX request to a Rails controller that uses before_filter
to authenticate the user. The prob开发者_JAVA百科lem is when the request gets sent, the server asks for authentication even if the user is already logged in.
Here is my AJAX request:
$.ajax({
type: 'DELETE',
url: "/messages/delete_all",
data: [1,2,4],
success: function() {
console.log("Your request is received.")
}
});
When the user hits delete_all
from the browser, it works, but with AJAX it doesn't. What gives?
EDIT: could it be related to the authenticity_token
?
Maybe this question will help: Using javascript with the twitter API
The solution proposed there should look something like this in your case
$.ajax({
type: 'DELETE',
url: "/messages/delete_all",
data: [1,2,4],
beforeSend: function(xhr) {
xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password)
},
success: function() {
console.log("Your request is received.")
}
});
精彩评论