laravel 5 ajax请求

时间:2015-07-03 09:09:35

标签: ajax laravel laravel-5

我在laravel中有一个用户列表表单。所以当我点击表格行时,它会自动从数据库加载用户详细信息而不重定向。我听说过ajax。但我不知道如何在laravel中使用它..

我想这样做enter image description here

enter image description here

但没有重定向页面..

$("tr").click(function() 
    {
        $.ajax({
          type: "GET",
          url: $(this).data("href"),
          dataType: "text",
          success : function(data) {
                      $('#details-container').load(data)
                    }
        });
    });

它应该是这样的吗?但我是如何从数据库中获取数据的呢?我不知道。请帮帮我..

2 个答案:

答案 0 :(得分:1)

在Laravel中与在"本地"中相同。 PHP。使用您的Ajax请求,您可以发送和异步请求,并只刷新您网站的一小部分,因此您无需重新加载整个页面。

如果你想使用laravel,你应该:

  1. 为您的请求创建路线

    Route::get('user/{id}', function($id)
    {
        // So all your GET requests with any user id goes to this script (in routes.php) 
    
        // here you should load your user information, maybe with ORM
    
        $user = User::where('id','=',$id)->get();
    
       // Build any HTML snippet, or build JSON data (and build the information in Javascript on your page)
    
     //return here JSON / or html
     $data = array() -> containts information for the blade template
     return view('users.information', $data);
    
    });
    
  2. 您的AJAX请求现在返回JSON /或HTML,将其附加到您要显示它的网站。

答案 1 :(得分:1)

您的页面结构如下:

<table>
  <thead>
    ...
  </thead>

  <tbody>
    <tr data-details-link="http://your-domain/user/{user-id}/details">
      ...
    </tr>
  </tbody>
</table>

带有表的页面应该有这个jQuery代码:

$('table tr').on('click', function (event)
{
  event.preventDefault();

  var $this = $(this);

  // not necessary but you should show a loading here

  $.ajax({
    url: $this.data('details-link')
  })
    .success(function (response)
    {
      // the `response` variable is HTML code. Insert it into a modal.
    });
});

您的路线:

...
Route::get('user/{id}/details', [ 'uses' => 'UserController@details' ]);
...

您的UserController方法:

public function details($id)
{
  $user = \App\User::find($id);

  if (!$user)
    abort(404);

  return view('user.details')->with('user', $user);
}

**您的user/details.blade.php应该包含将作为AJAX响应发送的HTML。

相关问题