2015-12-26 171 views
2

如何使用ajax(laravel)從mysql數據庫獲取數據?如何更新塊動態.message_box如何使用ajax(laravel)從mysql數據庫獲取數據?

AJAX

$(function() { 

$.ajax({ 
    url: "", 
    dataType: 'html', 

    success: function(responce){ 
     $('.message_box').html(responce); // this div to be updated 
    } 
}); 

});

刀片

<div class="message_box"> 

    @foreach($message as $content) 
     {{ $content->message }} 
    @endforeach 

</div> 

控制器

public function chat() 
{ 
    $message = MessageModel::orderBy('id')->get(); 
    return view('chat.chat', ['message' => $message]); 
} 

更新代碼

+1

哪裏是數據庫查詢?問題是什麼? – undefined

+0

@Vohuman,更新代碼 –

回答

3

你一個網址添加到您的Ajax請求?

路線

Route::get('/chat', '[email protected]'); 

AJAX

 function update() { 
     $.ajax({ 
      url: "/chat", 
      dataType: 'html', 

      success: function(responce){ 
       $('.message_box').html(responce); 
      } 
     }); 
    } 

    $('#send_message').submit(function (event) { 
     event.preventDefault(); 

     $.ajax({ 
      type: "post", 
      url: "/chat", 
      context: this, 
      data: $(this).serialize(), 
      cache: false, 
      async: true, 

      success: function() { 
       $('#message').val(''); 
       update(); 
      }, 

      error: function() { 
       alert('Сообщение не было отправлено'); 
      } 
     }); 

    }); 
+0

是的,但.message_box沒有更新(如果添加新內容)。 –

+0

ajax只被調用一次;當頁面第一次加載時。聊天是實時的嗎? – Beardslapper

+0

是的,實時聊天。 –

相關問題