Update a Rails 3 partial using AJAX (not a form)

前端 未结 1 2016
不知归路
不知归路 2021-01-01 03:05

I found a number of questions and answers regarding updating a partial using Ajax after submitting a form. But my question is ?simpler?, I just want to reload a partial ever

相关标签:
1条回答
  • 2021-01-01 03:21

    Well it turns out the answer is a little complicated:

    Step 1: Use Javascript's setInterval function along with jQuery's $.get() function to load a page, say /users/1/posts/latest.

    setInterval(function(){
      $.get("/users/1/posts/latest.js", function(data){
        $("latest_post").html(data);
      },
      "html")
    }, 30000);
    

    Step 2: Create a latest.js.erb and put it in your app/views/posts folder.

    Contents of latest.js.erb:

    <%= render partial: 'posts/latest', object: @user.posts.last, as: :post %>
    

    Step 3: Create the above partial with whatever you'd like (if you don't need a partial, you can just write the entire contents of the div in the latest.js.erb file.)

    Step 4: Add a latest method to your PostsController, that defines @user, etc. for the latest.js.erb to use.

    Step 5: Add get '/latest' to your routes.rb

    0 讨论(0)
提交回复
热议问题