Is it possible to refresh partial frequently using Ajax?

前端 未结 3 1016
旧时难觅i
旧时难觅i 2020-12-01 08:27

In background, I want it to reload and shows the number how many unread messages are there.
I want that without refreshing page. I mean using ajax.

If I had t

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 08:59

    You will use setInterval to send the ajax request:

    $(document).ready(function () {
        // will call refreshPartial every 3 seconds
        setInterval(refreshPartial, 3000)
    
    });
    
    // calls action refreshing the partial
    function refreshPartial() {
      $.ajax({
        url: "whatever_controller/refresh_part"
     })
    }
    

    Then you make an action in a controller like this:

    def refresh_part
      # get whatever data you need to a variable named @data
      respond_to do |format|
        format.js
      end
    end
    

    then you will write a js file named refresh_part.js.haml (you could erb instead of haml).

    refresh_part.js.haml would look like this:

    $('#part_you_want_to_refresh').html("#{escape_javascript(render 'name_of_partial', data: @data)}");
    

    make sure you set the correct routes in routes.rb.

提交回复
热议问题