Laravel - 使用 Ajax 从数据库中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33190808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:31:58  来源:igfitidea点击:

Laravel - Using Ajax to Fetch Data From Database

javascriptphpjqueryajaxlaravel

提问by senty

I am trying fetch data on-click on a button.

我正在尝试单击按钮获取数据。

This is how I return data in my controller:

这就是我在控制器中返回数据的方式:

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

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

And this is the jQuery file:

这是 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);
              }
          });
      });
 });

'loading please wait' part is working but on success, I couldn't make it prompt. What I am missing?

“正在加载请稍候”部分正在运行,但成功后,我无法提示。我缺少什么?

回答by Jeremie Ges

Your Laravel method:

你的 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);
}

And your javascript.

还有你的 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);
    });


  });

});