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

如何在非button按钮/无fetch的情况下触发Bootstrap Toast?

简便触发Bootstrap Toast的两种方案

针对你的表单提交场景,不需要依赖type="button"按钮或fetch,有两种直接的实现方式:

方案一:表单提交后页面刷新触发Toast(适合普通表单提交流程)

这种方式利用PHP会话传递状态,页面加载时自动检测并弹出Toast,完全贴合你现有的PHP处理逻辑:

  1. 先在页面中定义Bootstrap Toast结构(默认隐藏):
<div class="toast position-fixed bottom-0 end-0 m-3" role="alert" aria-live="assertive" aria-atomic="true" id="successToast">
  <div class="toast-header">
    <strong class="me-auto">操作成功</strong>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    数据已成功保存至JSON文件!
  </div>
</div>
  1. PHP处理表单时设置会话标记:
    在你的PHP处理文件中,完成JSON保存后,设置会话变量标记需要显示Toast,然后跳回表单页面:
<?php
session_start();
// 此处是你保存数据到JSON文件的代码...

// 设置会话标记,告知前端需要显示Toast
$_SESSION['show_toast'] = true;

// 跳回表单页面
header("Location: your-form-page.php");
exit;
?>
  1. 表单页面加载时检测并触发Toast:
    在表单页面的JS部分,通过PHP输出条件判断,页面加载时自动调用Toast的show()方法:
<?php session_start(); ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
  <?php if(isset($_SESSION['show_toast']) && $_SESSION['show_toast']): ?>
    const toast = new bootstrap.Toast(document.getElementById('successToast'));
    toast.show();
    // 清除会话标记,避免刷新页面重复显示
    <?php unset($_SESSION['show_toast']); ?>
  <?php endif; ?>
});
</script>

方案二:无刷新提交表单并触发Toast(用原生XMLHttpRequest替代fetch)

如果不想页面刷新,用原生XMLHttpRequest处理表单提交,提交完成后直接触发Toast:

  1. 保留Toast结构和原表单(表单按钮还是type="submit"):
<form method="POST" action="your-php-file.php" id="dataForm">
  <!-- 你的表单字段 -->
  <button type="submit" class="btn btn-primary">提交数据</button>
</form>

<!-- Toast结构同方案一 -->
<div class="toast position-fixed bottom-0 end-0 m-3" role="alert" aria-live="assertive" aria-atomic="true" id="successToast">
  <div class="toast-header">
    <strong class="me-auto">操作成功</strong>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    数据已成功保存至JSON文件!
  </div>
</div>
  1. 添加原生JS监听表单提交事件:
document.getElementById('dataForm').addEventListener('submit', (e) => {
  e.preventDefault(); // 阻止表单默认刷新行为

  const formData = new FormData(e.target);
  const xhr = new XMLHttpRequest();

  xhr.open('POST', e.target.action, true);
  xhr.onload = () => {
    if (xhr.status === 200) {
      // 提交成功后触发Toast
      const toast = new bootstrap.Toast(document.getElementById('successToast'));
      toast.show();
      // 可选:重置表单
      e.target.reset();
    }
  };

  xhr.send(formData);
});

两种方案都不需要额外的type="button"按钮或fetch方法,完全贴合你的需求。

内容的提问来源于stack exchange,提问作者al-naba project

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:53:17