簡體   English   中英

Laravel-使用Ajax從數據庫中獲取數據

[英]Laravel - Using Ajax to Fetch Data From Database

我正在嘗試在按鈕上單擊獲取數據。

這是我在控制器中返回數據的方式:

public function fetch()
    {
        $channels = Channel::where('channel', \Auth::user()->username)
            ->orderBy('created_at','desc')->take(3)->get();

        View::share ('channels', $channels);
    }

這是jQuery文件:

$( document ).ready(function() {
     $('#dropdownMenu').click(function() {
          $.ajax({
              type: "GET",
              dataType: "html",
              url: "channels/fetch",
              beforeSend: function() {
                    $('.testdropdown').html('loading please wait...');
              },
              success: function(htmldata) {
                  console.log(htmldata);
              }
          });
      });
 });

“正在加載,請稍候”部分正在運行,但是成功了,我無法及時提示。 我缺少什么?

您的Laravel方法:

public function fetch()
{
  $username = \Auth::user()->username;

  $channels = Channel::where('channel', $username)->orderBy('created_at', 'desc')->take(3)->get();

  // Return as json
  return Response::json($channels);
}

還有你的javascript。

$(document).ready(function() {

  $('#dropdownMenu').on('click', function() {

    // Add loading state
    $('.testdropdown').html('Loading please wait ...');

    // Set request
    var request = $.get('/channels/fetch');

    // When it's done
    request.done(function(response) {
      console.log(response);
    });


  });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM