@formspree/ajax

中文文档
1.1.5发布于 2026/03/17MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2145

The AJAX library for Formspree

原始使用文档
文档目录13 节
  1. Installation
  2. NPM / Yarn
  3. Script Tag (CDN)
  4. Quick Start
  5. ESM (with a bundler)
  6. HTML
  7. Data Attributes
  8. Configuration
  9. Lifecycle Callbacks
  10. Default Behaviors
  11. Extra Data
  12. Styling
  13. Help and Support

Formspree AJAX

A vanilla JavaScript library for declarative form handling with Formspree. No framework required — works with plain HTML forms via data attributes or a simple JavaScript API.

Installation

NPM / Yarn

npm install @formspree/ajax

yarn add @formspree/ajax

Script Tag (CDN)

No bundler needed. Add this snippet before the closing </body> tag:

<script>
  window.formspree =
    window.formspree ||
    function () {
      (formspree.q = formspree.q || []).push(arguments);
    };
  formspree('initForm', { formElement: '#my-form', formId: 'YOUR_FORM_ID' });
</script>
<script src="https://unpkg.com/@formspree/ajax@1" defer></script>

Quick Start

ESM (with a bundler)

import { initForm } from '@formspree/ajax';

initForm({
  formElement: '#contact-form',
  formId: 'YOUR_FORM_ID',
});

HTML

<div data-fs-success></div>
<div data-fs-error></div>

<form id="contact-form">
  <label for="email">Email</label>
  <input type="email" id="email" name="email" data-fs-field />
  <span data-fs-error="email"></span>

  <button type="submit" data-fs-submit-btn>Send</button>
</form>

That's it. The library handles submission, validation errors, loading state, and success messages automatically.

Data Attributes

These HTML attributes enable declarative form behavior without additional JavaScript:

AttributeElementDescription
data-fs-error="fieldName"<span>, <div>Displays field-level validation errors. If empty, the API error message is injected. If it has content, it is shown/hidden as-is.
data-fs-error<div>Displays form-level errors (without a value). Same content policy: empty elements get the server message, elements with content are shown as-is.
data-fs-success<div>Displays a success message after submission. Empty elements get "Thank you!", elements with content are shown as-is.
data-fs-field<input>, <textarea>Marks an input to receive aria-invalid="true" on error. The field name is read from the element's name attribute.
data-fs-submit-btn<button>Automatically disabled during submission and re-enabled on completion.

Configuration

Pass a config object to initForm():

import { initForm } from '@formspree/ajax';

const handle = initForm({
  // Required
  formElement: '#contact-form', // CSS selector or HTMLFormElement
  formId: 'YOUR_FORM_ID', // Your Formspree form ID

  // Optional
  origin: 'https://formspree.io', // API origin (default)
  debug: false, // Enable console logging

  // Extra data merged into every submission
  data: {
    source: 'website',
    campaign: () => getCampaign(),
    timestamp: async () => await getServerTime(),
  },

  // Lifecycle callbacks
  onInit: (context) => {},
  onSubmit: (context) => {},
  onSuccess: (context, result) => {},
  onError: (context, error) => {},
  onFailure: (context, error) => {},

  // Custom rendering (override defaults)
  enable: (context) => {},
  disable: (context) => {},
  renderFieldErrors: (context, error) => {},
  renderSuccess: (context, message) => {},
  renderFormError: (context, message) => {},
});

// Clean up when done
handle.destroy();

Lifecycle Callbacks

CallbackArgumentsDescription
onInit(context)Called when the form is initialized.
onSubmit(context)Called before submission is sent.
onSuccess(context, result)Called on successful submission.
onError(context, error)Called on validation errors from Formspree.
onFailure(context, error)Called on unexpected errors (e.g., network failure).

The context object contains: form (HTMLFormElement), formKey, endpoint, client, and config.

Default Behaviors

The library provides sensible defaults out of the box:

  • Submit button — Disabled during submission, re-enabled on completion.
  • Field errors — Populated into data-fs-error="fieldName" elements. If the element is empty, the API error message is injected. If it has content, it is shown/hidden as-is.
  • Field validation — aria-invalid="true" is set on data-fs-field inputs when their field has errors.
  • Success message — The data-fs-success element is shown with "Thank you!" (or preserved user content).
  • Form errors — The data-fs-error element (without a value) is shown with the form-level error message (or preserved user content).
  • Success without data-fs-success — If no data-fs-success element exists and no onSuccess callback is provided, the form is replaced with a "Thank you!" message.
  • Success with data-fs-success — If a data-fs-success element exists and no onSuccess callback is provided, the form is reset after success.
  • Default styles — Basic styles for error messages, invalid fields, and message banners are automatically injected.

Extra Data

Append extra data to every submission using the data option. Values can be static strings, sync functions, or async functions. undefined values are skipped.

initForm({
  formElement: '#my-form',
  formId: 'YOUR_FORM_ID',
  data: {
    source: 'landing-page',
    referrer: () => document.referrer || undefined,
    sessionId: async () => await fetchSessionId(),
  },
});

Styling

Default styles are injected automatically. You can override them with your own CSS:

/* Error message text */
[data-fs-error] {
  color: #dc3545;
  font-size: 12px;
}

/* Invalid field border */
[data-fs-field][aria-invalid='true'] {
  border-color: #dc3545;
}

/* Success message banner */
[data-fs-success][data-fs-active] {
  background: #d4edda;
  color: #155724;
}

/* Form-level error banner */
[data-fs-error=''][data-fs-active] {
  background: #f8d7da;
  color: #721c24;
}

Help and Support

For help and support please see the Formspree docs.

版本与发布记录

@formspree/ajax 共发布 3 个版本,首次发布于 2026/02/25;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.5latest2026/03/178 个月前
1.1.02026/02/258 个月前
1.0.02026/02/258 个月前

关于 @formspree/ajax 的常见问题

@formspree/ajax 是什么?

The AJAX library for Formspree

如何安装 @formspree/ajax?

在项目目录运行 npm install @formspree/ajax,或使用 pnpm add / yarn add / bun add。

@formspree/ajax 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@formspree/ajax 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@formspree/ajax 可以商用吗?

@formspree/ajax 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@formspree/ajax 的下载量有多少?

根据 npm 官方下载统计,@formspree/ajax 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,145 次,日均约 72 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@formspree/ajax 还在维护吗?

最新版本 1.1.5 发布于 2026/03/17(8 个月前);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/02/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。