DDR爱好者之家 Design By 杰米

开发H5项目的时候我们总是需要用到下拉滚动刷新的方式加载页面。这里用 Laravel 实现一下,直接上代码:

创建模型

这里我们不妨创建一个 文章(Post)模型, 并且生成测试数据 50 条吧。

php artisan make:model -m

模型Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

 public $fillable = ['title','description'];

 
}

迁移文件

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostTable extends Migration
{
 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
  Schema::create('posts', function (Blueprint $table) {
   $table->increments('id');
   $table->string('title');
   $table->text('description');
   $table->timestamps();
  });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::drop("posts");
 }
}

测试数据 ModelFactory.php

$factory->define(App\Post::class, function (Faker\Generator $faker) {
 return [
  'title' => $faker->sentence,
  'description' => $faker->paragraph,
 ];
});

填充

<"htmlcode">
Route::get('my-post', 'PostController@myPost');

控制器

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;

class PostController extends Controller
{

 public function myPost(Request $request)
 {
  $posts = Post::paginate(6); 

  if ($request->ajax()) {
   $view = view('data',compact('posts'))->render();
   return response()->json(['html'=>$view]);
  }

  return view('my-post',compact('posts'));
 }

}

视图文件 resources/view/my-post.php

<!DOCTYPE html>
<html>
<head>
 <title>Laravel 分页滚动加载</title>
 <script src="/UploadFiles/2021-04-02/jquery.min.js">

resources/view/data.php

@foreach($posts as $post)
<div>
 <h3><a href="">{{ $post->title }}</a></h3>
 <p>{{ str_limit($post->description, 400) }}</p>

 <div class="text-right">
  <button class="btn btn-success">Read More</button>
 </div>

 <hr style="margin-top:5px;">
</div>
@endforeach

效果:

Laravel 简单实现Ajax滚动加载示例

以上这篇Laravel 简单实现Ajax滚动加载示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米