laravel如何将分页结果发送到ajax请求

时间:2018-07-09 12:06:52

标签: ajax laravel

在laravel中,使ajax中的视图调用页面未正确加载。页面加载如下图所示。enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试Eloquent Resource

  1. 使用以下命令生成资源类:

    php artisan make:resource User
    

    注意::使用您自己的型号名称代替User

  2. 然后使用以下命令创建资源收集类:

    php artisan make:resource UserCollection
    

    php artisan make:resource Users --collection
    
  3. 返回对ajax的响应,如下所示:

    public function getUsers() {
        $users = User::paginate();
    
        /**
         * this will convert your collection into array and 
         * also sends the additional pagination information.
         */
        return new UserCollection($users);
        // or 
        // return new Users($users);
    }
    

此外,您可以像这样在资源中的toArray()中管理/转换响应:

class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
相关问题