Laravel Ajax Builder 是一个用于轻松创建 AJAX JSON 响应的 Laravel 扩展包。它允许通过流畅的接口设置状态码、消息、视图、数据、警告和重定向 URL,从而简化在 Laravel 应用程序中发送 AJAX 响应的过程。

0.4 2024-08-04 09:44 UTC

This package is auto-updated.

Last update: 2024-09-04 09:56:13 UTC


README

Latest Version Stars Total Downloads Forks Issues Linkedin

此包为在 Laravel 应用程序中实现 jQuery AJAX 调用和管理响应提供了一个简单的解决方案。

为了提升用户体验,强烈建议将此包与 Laravel Tablar 管理仪表板集成。

安装

composer require takielias/lab
php artisan lab:install

现在运行 npm run dev

用法

在 Blade 文件中需要显示警告信息的位置插入 @alert。将表单提交按钮设置为 @submit

示例

<form class="card" action="{{route('product.save')}}" method="post">
    <div class="card-header">
        <h3 class="card-title">Slip form</h3>
    </div>
    <div class="card-body">
        @alert
        
      ...............
      ...............
      
    </div>
    <div class="card-footer text-end">
        @submit
    </div>
</form>

控制器

    function store(SaveProductRequest $saveProductRequest)
    {
        $validated = $saveProductRequest->validated();
        Product::create($validated);
        return Lab::setData(['success' => true])
            ->enableScrollToTop()
            ->setRedirect(route('product.index'))
            ->setSuccess('Product Created Successfully')
            ->setStatus(201)
            ->toJsonResponse();
    }

请求

用于请求验证

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Takielias\Lab\Facades\Lab;

class SaveProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
            'price' => ['required', 'gt:0'],
            'name' => ['required']
        ];
    }

    protected function failedValidation($validator)
    {
        // Throw the HttpResponseException with the custom response
        throw new HttpResponseException(Lab::setStatus(422)
            ->enableScrollToTop()
            ->setValidationError($validator)->toJsonResponse());
    }
}

AJAX 调用

    const productData = {
    product_name: 'Product Name'
    };
    const postUrl = '{{route('
    product.save
    ')}}';
    ajaxPost(postUrl, productData, function (response) {
        console.log(response.data)
    }, function (error) {
    
    }, function (data) {
    
    })

还有一些内置方法:ajaxGet、ajaxPost、ajaxPut 和 ajaxPatch

变更日志

有关最近更改的详细信息,请参阅 变更日志

测试

composer test

贡献

有关详细信息和一个待办事项列表,请参阅 contributing.md

安全

如果您发现任何安全相关的问题,请通过电子邮件 taki.elias@email.com 而不是使用问题跟踪器来报告。

致谢

许可

MIT。有关更多信息,请参阅 许可文件