laravelÔõôʵÏÖajax·ÖÒ³
laravelʵÏÖajax·ÖÒ³
Ëæ×Å»¥ÁªÍøµÄÉú³¤ºÍÊÖÒÕµÄÇ°½ø£¬ÏÖ´úWebÓ¦ÓóÌÐò¹ØÓÚÓû§ÌåÑéµÄÒªÇóÔ½À´Ô½¸ß¡£¶øÔÚÕâÑùµÄÓ¦ÓóÌÐòÖУ¬·ÖÒ³ÊDz»¿É»òȱµÄÒ»¸ö¹¦Ð§¡£ÔڹŰåµÄ·ÖÒ³·½·¨ÖУ¬Ê¹ÓùŰåµÄÒ³ÃæË¢ÐÂÒªÁì¾ÙÐÐÒ³ÂëÌøתºÍÊý¾Ý¼ÓÔØ£¬ÕâÑù»áµ¼ÖÂÓû§ÌåÑéµÄ½µµÍ£¬ÌØÊâÊÇÊý¾ÝÁ¿ÖØ´óʱ£¬Óû§ÐèÒªÆÚ´ý½Ï³¤Ê±¼ä²Å»ª¿´µ½ÏëÒªµÄÄÚÈÝ¡£Òò´Ë£¬Ò»ÖÖеķÖÒ³·½·¨±»ÆÕ±éʹÓ᪡ªAjax·ÖÒ³¡£
Laravel¿ò¼ÜÌṩÁËÇ¿Ê¢µÄÖ§³Ö£¬²¢ÇÒ¿ÉÒÔÈÃÎÒÃÇÇáËɵØʵÏÖAjax·ÖÒ³¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃlaravelʵÏÖajax·ÖÒ³¡£
ÉèÖ÷ÓÉ
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÉèÖ÷ÓÉÀ´Ö§³ÖAjax·ÖÒ³¡£ÔÚweb.phpÎļþÖÐÌí¼ÓÏÂÃæµÄ·ÓÉ£º
Route::get('/posts', 'PostController@index'); Route::get('/posts/fetch_data', 'PostController@fetch_data');
µÇ¼ºó¸´ÖÆ
½¨Éè¿ØÖÆÆ÷
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸ö¿ØÖÆÆ÷À´´¦ÀíÇëÇó¡£ÔËÐÐÒÔÏÂÏÂÁîÔÚLaravelÖн¨ÉèPostController£º
php artisan make:controller PostController
µÇ¼ºó¸´ÖÆ
ÔÚPostControllerÖÐÌí¼ÓÒÔÏ´úÂ룺
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; class PostController extends Controller { public function index() { $posts = Post::paginate(5); return view('posts.index', compact('posts')); } public function fetch_data(Request $request) { if($request->ajax()) { $posts = Post::paginate(5); return view('posts.data', compact('posts'))->render(); } } }
µÇ¼ºó¸´ÖÆ
ÎÒÃÇʹÓÃpaginateÒªÁìÀ´»ñÈ¡Ìû×ÓÊý¾Ý¡£ÔÚfetch_dataÒªÁìÖУ¬ÎÒÃÇʹÓÃÒ»¸öÃûΪdataµÄbladeÊÓͼÀ´·ºÆðÊý¾Ý£¬ÈçÏÂËùʾ£º
<div> @foreach($posts as $post) <div> <div> <img alt="laravelÔõôʵÏÖajax·ÖÒ³" >image }}" alt="{{ $post->title }}"> <div> <h5>{{ $post->title }}</h5> <p>{{ $post->excerpt }}</p> <a>Read More</a> </div> </div> </div> @endforeach </div>
µÇ¼ºó¸´ÖÆ
½¨ÉèÊÓͼ
ÏÖÔÚ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öÊÓͼÀ´ÏÔʾÌû×ÓÊý¾Ý²¢ÆôÓÃAjax·ÖÒ³¡£ÔÚresources/views/posts/index.blade.phpÎļþÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
@extends('layouts.app') @section('content') <div> <div> @include('posts.data') </div> <div> {{ $posts->links() }} </div> </div> @endsection @section('scripts') <script> $(document).ready(function() { $(document).on('click', '.pagination a', function(e) { e.preventDefault(); var page = $(this).attr('href').split('page=')[1]; fetch_data(page); }); }); function fetch_data(page) { $.ajax({ url:"/posts/fetch_data?page="+page, success:function(data) { $('#posts').html(data); } }); } </script> @endsection
µÇ¼ºó¸´ÖÆ
ÔÚÕâÀÎÒÃÇʹÓÃÁËbladeµÄ@paginationÖ¸ÁîÀ´·ºÆðÒ³ÂëÁ´½Ó£¬Í¬Ê±°üÀ¨data.blade.phpÖеÄÊý¾Ý¡£ÔÚ@scriptsÖ¸ÁîÖУ¬ÎÒÃÇʹÓÃjQueryÀ´´¦Àíµã»÷ÊÂÎñ²¢·ºÆðÊý¾Ý¡£
½¨ÉèÑùʽ
×îºó£¬ÎÒÃÇÐèÒªÌí¼ÓһЩÑùʽ£¬Ê¹Ò³Ãæ¿´ÆðÀ´¸üƯÁÁ¡£ÔÚpublic/css/app.cssÎļþÖÐÌí¼ÓÒÔÏ´úÂ룺
.card { border: none; } .card-text { color: #555; } .card-img-top { height: 220px; object-fit: cover; }
µÇ¼ºó¸´ÖÆ
ÏÖÔÚÎÒÃǵÄLaravelÓ¦ÓóÌÐò¾Í×¼±¸ºÃʹÓÃAjax·ÖÒ³ÁË£¡µ±Óû§µã»÷Ò³ÂëÁ´½Óʱ£¬Ò³Ã潫ÎÞÐèˢжø¼ÓÔØÊý¾Ý¡£ÕâÑù¿ÉÒÔ´ó´óÌá¸ßÓû§ÌåÑ飬ÓÈÆäÊÇÔÚÊý¾ÝÁ¿ÌØÊâ´óµÄÇéÐÎÏ¡£
×ܽá
±¾ÎÄÏÈÈÝÁËÔõÑùʹÓÃLaravel¿ò¼ÜÀ´ÊµÏÖAjax·ÖÒ³¡£Í¨¹ýʹÓÃAjax·ÖÒ³£¬¿ÉÒÔ¼«´óµØÌá¸ßÓû§ÔÚÄúµÄWebÓ¦ÓóÌÐòÖеÄÌåÑ飬ÓÈÆäÊÇÔÚÊý¾ÝÁ¿´óµÄÇéÐÎÏ¡£Ê¹ÓÃLaravel¿ò¼Ü£¬ÎÒÃÇ¿ÉÒÔÇáËɵØʵÏÖÕâÒ»¹¦Ð§£¬²¢ÓÅ»¯ÎÒÃǵÄÓ¦ÓóÌÐò¡£Ï£ÍûÕâƪÎÄÕ¶ÔÄúÓÐËù×ÊÖú£¡
ÒÔÉϾÍÊÇlaravelÔõôʵÏÖajax·ÖÒ³µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡