crudadmin/autoajax

Laravel或纯PHP的自动Ajax表单提交

2.0.8 2024-07-16 14:04 UTC

This package is auto-updated.

Last update: 2024-09-16 14:25:49 UTC


README

PHP库管理javascript库autoAjax.js的HTTP响应。该软件包旨在与Laravel/PHP协同工作,处理VueJs/PlainJS表单提交,并自动管理从验证响应中接收到的自动表单验证。

Example

这是软件包的一部分,用于在应用程序的PHP/Laravel端实现。更多关于本软件包的JavaScript/VueJs部分,请参阅autoAjax.js

特性

  • 自动从表单输入构建请求数据。
  • 自动将Laravel验证的验证错误消息绑定到每个输入。
  • VueJs集成
  • PlainJs集成

Composer安装

composer require "crudadmin/autoajax"

使用方法

在Laravel控制器响应中

public function store()
{
    //...

    return autoAjax()->success('Thank you! Your for has been successfully sent.');
}

如果您需要抛出错误消息,您需要使用throw()render()方法。

//...

//Script dies here
autoAjax()->success('Thank you! Your for has been successfully sent.')->throw();

//...

API

//Success messages.
autoAjax()->success('Success message');
autoAjax()->message('Success message');
autoAjax()->save(); //Global success message will be applied.

//Error messages
autoAjax()->error('Error message with 200 HTTP code');
autoAjax()->error('Error message with 500 HTTP code', 500);
autoAjax()->error('Error message with 500 HTTP code')->code(500);
autoAjax()->error(); //Global error message will be applied.

//Change title of response
autoAjax()->message('Success message')->title('My response title');
autoAjax()->error('Error message')->title('My response title');

//Change HTTP code
autoAjax()->message('My message')->code(500);

//If you want redirect/reload request after response comes. (autoAjax.js will handle it)
autoAjax()->redirect('https://google.com');
autoAjax()->reload();

//If you need run own JS callback after response
autoAjax()->title('This is my message')->callback('alert(1)');

//If you want modify all success/error messages globally. You can do it in AppServiceProvider or somewhere else in your app configuration like that.
autoAjax()->setGlobalMessage('success', 'Changes has been successfully saved.');
autoAjax()->setGlobalMessage('error', 'Something went wrong. Try again later.');

JSON响应

{
  callback: null,
  data: [],
  error: false,
  message: "Custom message",
  redirect: null,
  title: "Success",
  type: "message",
}

callback - autoAjax库的JavaScript回调

data - 为autoAjax库和您的VueJs或PlainJs应用程序的响应提供的附加数据数组

error - 响应是错误类型吗?

message - 输出消息。

redirect - 响应请求后应将用户重定向到的URL。AutoAjax.js将处理它。

title - 您自定义的模态消息标题。

type - 消息或模态。您可以自定义您的响应以用于警报消息或模态窗口。

验证响应

您可以使用Laravel验证器抛出验证响应。

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

您也可以使用throwValidation方法自行抛出验证消息。

autoAjax()->throwValidation([
    'username' => 'Validation message for username',
    'password' => 'Validation message for password',
]);

或者,手动发送带有错误代码422 Unprocessable Entity的JSON请求。

{
    "email": ["Please fill this field."],
    "phone": ["Please fill this field."]
}