首页 > 解决方案 > laravel如何将分页结果发送到ajax请求中

问题描述

在 ajax 调用中的 laravel make view 中,页面未正确加载。它像下图一样加载。在此处输入图像描述

在此处输入图像描述

标签: ajaxlaravel

解决方案


你可以试试雄辩的资源

  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,
        ];
    }
}

推荐阅读