English 中文(简体)
Rails: Ajax: Changes Onload
原标题:

I have a web layout of a for that looks something like this

<html>
  <head>
  </head>

  <body>
    <div id="posts">
      <div id="post1" class="post" >
         <!--stuff 1-->
      </div>
      <div id="post2" class="post" >
         <!--stuff 1-->
      </div>

      <!-- 96 more posts -->

      <div id="post99" class="post" >
         <!--stuff 1-->
      </div>
    </div>          

  </body>
</html>

I would like to be able to load and render the page with a blank , and then have a function called when the page is loaded which goes in and load up the posts and updates the page dynamically.

In Rails, I tried using "link_to_remote" to update with all of the elements. I also tweaked the posts controller to render the collection of posts if it was an ajax request (request.xhr?). It worked fine and very fast. However the update of the blank div is triggered by clicking the link. I would like the same action to happen when the page is loaded so that I don t have to put in a link.

Is there a Rails Ajax helper or RJS function or something in Rails that I could use to trigger the loading of the "posts" after the page has loaded and rendered (without the posts)?

(If putsch comes to shove, I will just copy the generated JS code from the link_to_remote call and have it called from the onload handler on the body).

最佳回答

Sure there is, it s Rails, after all :)

Something like that will do:

<% javascript_tag do %>
  $(document).ready(function() {
    <%= remote_function(:update => "posts", :url => posts_partial_path) %>
  });
<% end %> 

remote_function will give you the same javascript that gets executed when you use rails ajax helpers.

问题回答

Do this using jQuery unobtrusively like so:

$(document).ready(function(){
  $.ajax({url:  posts_partial_path ,
           success: function(data) {
             $( #posts ).html(data);
           }
  });
});

putting this code in a JavaScript file included by your page. You need to replace posts_partial_path above with the actual URL string, Rails helpers are not available in the JavaScript code. Read about making AJAX calls with jQuery here: http://api.jquery.com/jQuery.ajax/ . Works like a champ.

Walter Gillett





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签