You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel表单提交后如何显示页面加载器

在Laravel中实现表单提交时的加载器效果

方案一:原生JS+CSS实现

1. 调整按钮HTML结构

给按钮添加隐藏的加载图标元素,方便切换显示状态:

<button type="submit" id="submit" class="w-full px-3 py-3 font-medium text-white bg-green-400 rounded-lg flex items-center justify-center gap-2">
  <span>Request now</span>
  <svg class="hidden animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  </svg>
</button>

2. 补充CSS动画(不用Tailwind的话)

如果项目没用到Tailwind,自己定义加载动画:

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
.animate-spin {
  animation: spin 1s linear infinite;
}

3. 编写提交状态逻辑

监听表单提交事件,切换按钮状态并禁用重复提交:

document.addEventListener('DOMContentLoaded', function() {
  const form = document.querySelector('form'); // 替换成你的表单选择器
  const submitBtn = document.getElementById('submit');
  const btnText = submitBtn.querySelector('span');
  const loader = submitBtn.querySelector('svg');

  form.addEventListener('submit', function() {
    submitBtn.disabled = true;
    btnText.classList.add('hidden');
    loader.classList.remove('hidden');
  });
});

方案二:Livewire内置加载状态(如果用Livewire)

如果项目基于Livewire开发,直接用它的内置指令实现:

<button type="submit" id="submit" class="w-full px-3 py-3 font-medium text-white bg-green-400 rounded-lg" wire:loading.attr="disabled" wire:loading.class="bg-gray-400">
  <span wire:loading.remove>Request now</span>
  <span wire:loading class="flex items-center justify-center gap-2">
    <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
    </svg>
    Loading...
  </span>
</button>

Livewire会自动在请求处理期间切换加载状态,无需额外JS。

额外注意

如果是AJAX提交(比如用Axios),要在请求完成后恢复按钮状态:

axios.post(form.action, new FormData(form))
  .then(res => { /* 处理成功逻辑 */ })
  .catch(err => { /* 处理错误逻辑 */ })
  .finally(() => {
    submitBtn.disabled = false;
    btnText.classList.remove('hidden');
    loader.classList.add('hidden');
  });

内容的提问来源于stack exchange,提问作者Ibegbunem Aniemeke Lawson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:01:16