如何使用ajax(laravel)从mysql数据库中获取数据?如何动态更新块.message_box
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]);
}
更新了代码
答案 0 :(得分:3)
您是否在ajax请求中添加了网址?
Route::get('/chat', 'ChatController@chat');
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('Сообщение не было отправлено');
}
});
});