简体   繁体   English

如何使用ajax(laravel)从mysql数据库中获取数据?

[英]How fetch data from a mysql database using ajax (laravel)?

How fetch data from a mysql database using ajax (laravel)? 如何使用ajax(laravel)从mysql数据库中获取数据? How to update the block dynamically .message_box 如何动态更新块.message_box

AJAX AJAX

$(function () {

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

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

}); });

Blade

<div class="message_box">

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

</div>

Controller 调节器

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

Updated code 更新的代码

Did you add a url to your ajax request? 您是否向ajax请求添加了网址?

Routes 路线

Route::get('/chat', 'ChatController@chat');

AJAX 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('Сообщение не было отправлено');
            }
        });

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM