Rails: format.js redirecting me to a blank page
I just for the life of me cannot get an AJAX call to work correctly
Here is my button:
<%= button_to "Click me!", :action => "seen", :controller=>"notifications", :remote => true %>
Here is my controller:
def seen
respond_to do |format|
format.js
end
end
Here is my route:
match 'notifications/seen', :to => "notifications#seen"
Here is my file app/views/notifications/seen.js.erb in the :
$(document).ready(function(){
$("button").trigger(function(){
$("div#count").html("
Notifications: <%= current_user.notification_unseen %>
" )notification_ids = current_user.notifications.map(&:id).join(', ')%>
<% sql = "UPDATE notifications SET SEEN = true where id IN(#{notification_ids})" %>
开发者_开发问答 <% User.connection.select_all(sql) %> });
});
Yet every time I click on the button, I get redirected to a blank page at this URL:
http://localhost:3000/notifications/seen?remote=true
The page is just completely blank...what am I doing wrong??? I am at a loss..(PS I want the user to stay on the same page and not be redirected elsewhere.)
If you are being redirected to a blank page, then the default action of the link is not being prevented. The page is blank because your controller will only respond to JS requests.
The :remote => true option in your button_to is a feature of Rails UJS, which is defined in rails.js. This code is responsible for wiring up the button click to an AJAX request when triggered. If you are using jQuery, you will need to ensure that the rails.js content is for jQuery, and not Prototype.js. Grab the jQuery rails.js file here: https://github.com/rails/jquery-ujs
You can also use the Firebug extension in Firefox, or the Inspector Tools in Chrome to ensure that you are not receiving a Javascript error, which could halt the execution of the AJAX request.
Just add curly braces and it will fix it.
<%= button_to "Click me!", {:action => "seen", :controller=>"notifications"}, :remote => true %>
fyi, it needs to generate a data-remote="true" in your form tag and not append remote as a parmeter (?remote=true) in your url.
精彩评论