Rails 3: Simple AJAXy Page updates?

北城以北 提交于 2019-11-28 20:46:03
Ed Jones

Thanks, guys. The official answer seems to be that, yes, the team felt simple is the enemy of good and made it more complicated.

The first key is to create a .js.erb file NAMED for the method CALLING the ajax update. So if the index method handles the update, put the raw javascript in index.js.erb. This goes in the views folder.

Second, the code that worked in index.js.erb was

m = $('list_users');    
m.innerHTML = "<%= escape_javascript(render :partial => "reload_users") %>";

Then to make the call, add in the respond_to block of the controller method, add:

format.js

Finally, the calling view has:

<%= link_to "Update User List", @reload_users_path, :remote => true %>

By the way, supposedly all the old pages using page.replace will work if you install a plugin. The plugin download page suggests that it broke in the last releases of Rails 3 and has not been fixed. Also, various bloggers will come to your home and birch-switch you if you use it.

The whole RJS stuff makes the javascript inline and makes the dom very obtrusive. Also, by avoiding inline javascript you could open up other possible ways of optimizing you javascript by compressing and caching those files in browser. Thats the reason why RJS is getting out of scope from rails 3. A little bit of getting around with jQuery or Prototype for a day should get you on gears with these kind of small stuff and will help the project on long run.

Do you still have jQuery in there? I'd recommend it over Prototype any day...

If it's still there you can just use the following in your Javascript:

$.get("<%= url_for path/to/partial %>",
      function(response) {
        $("#div_id").html(response);
      });

This gets the partial via AJAX and just dumps it into the div with id div_id.

Hope this helps!

I'm not even sure you need to make an AJAX call to load that partial. I believe that in a js.erb file, a call to render(:partial => object_or_path) will just return a string with all the html, which you can wrap in a jQuery object and append. Example:

$('#div_id').html($('<%= render :partial => @object %>'))

As far as I know, along the same line as the answer above, you can do something like this in your template:

<%= link_to "Update User List", @reload_users_path, :remote => true %>

And in controller, do this:

respond_to do |format|
  format.js {
    render :text => "alert('reloaded')"
  }
end

This way you can have controller "execute" client side JS much the same as as render :update used to do. This is equivalent to doing the following in Rails 2:

render :update do |page|
   page << "alert('reloaded')"
end

Is there any reason why this approach is not advisable?

Che

Try this:

page.call "$('#div_id').html", render(:partial => 'new_content')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!