LoginSignup
4
4

More than 5 years have passed since last update.

非同期の流れ 自動更新

Posted at

自動更新

スタート


setInterval(update, 2000) 

ここでリクエストを流す!!
controller の指定!!

 $.ajax({
      url: location.href,
      dataType: 'json',
      type: 'GET',
     data: { message_id: message_id },
 })


1. コントローラー起動
2. format.jsonで返す

 def index
    @message = Message.new

    @messages = @group.messages.includes(:user)
    respond_to do |format|
      format.html
      format.json { @new_messages = @messages.where('id > ?', params[:message_id]) }

    end

  end

変換

if @new_messages.present?
  json.messages @new_messages.each do |message|
  json.content       message.content
  json.image         message.image.url
  json.id            message.id
  json.name          message.user.name
  json.created_at  message.created_at
  end
end


1. doneで受ける
2. appendする

  .done(function(data) {
                data.forEach(function(message) {
                    $('.main-message-container').append(buildHTML(message));
                });
            })


data.forEach(function(message) {
                    $('.main-message-container').append(buildHTML(message));
                });

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4