使用 AJAX 和 vanilla JS 处理 Mailchimp 注册表单[重复]

Posted

技术标签:

【中文标题】使用 AJAX 和 vanilla JS 处理 Mailchimp 注册表单[重复]【英文标题】:Handle Mailchimp signup form with AJAX and vanilla JS [duplicate] 【发布时间】:2021-09-04 13:17:53 【问题描述】:

我有一个嵌入式 Mailchimp 注册表单,我想通过 AJAX 处理它。我已经按照这个问题的最佳答案 (AJAX Mailchimp signup form integration) 对 html 表单标记进行了编辑,但是我没有在我的项目中使用 jQuery,所以我尝试让它与 vanilla javascript 一起使用:

<form action="https://gmail.us6.list-manage.com/subscribe/post-json?u=XXX0&amp;id=XXX&amp;c=?" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>...</form>
const form = document.querySelector('#mc-embedded-subscribe-form');

form.addEventListener('submit', (e) => 
  e.preventDefault();

  fetch(e.target.action, 
    method: e.target.method,
    mode: 'no-cors',
    headers: 
      'Content-Type': 'application/json',
    ,
  )
    .then((response) => 
      return response.json();
    )
    .then((data) => 
      console.log(data);
    );
);

这会导致控制台出现以下错误:

Uncaught (in promise) SyntaxError: Unexpected end of input

jQuery 解决方案工作正常。有什么想法吗?

【问题讨论】:

去掉headers右括号后多余的逗号。 很遗憾,事实并非如此。 【参考方案1】:

action url 结果为 404。

因此,这是response.json(); 引发意外的输入结束

为避免 未捕获 错误,请在最后一个 then() 之后使用 catch() 块捕获它。

let form = document.querySelector("form");

form.addEventListener("submit", (e) => 
  e.preventDefault();

  fetch(e.target.action, 
    method: e.target.method,
    mode: "no-cors",
    headers: 
      "Content-Type": "application/json"
    
  )
    .then((response) => 
      if (!response.ok) 
        throw new Error("Request failed.");  // Custom message on the error to throw
       else 
        return response.json();  // Call .json() only on good responses
      
    )
    .then((data) => 
      console.log("data: " + data);
    )
    .catch((error) =>   // Catch the error here
      console.log("error: "+error);
    );
);

【讨论】:

以上是关于使用 AJAX 和 vanilla JS 处理 Mailchimp 注册表单[重复]的主要内容,如果未能解决你的问题,请参考以下文章

无法让 vanilla JS onreadystatechange 函数/readyState 4 工作

如何使用 Vanilla JavaScript/Ajax 获取地理位置 - 国家和城市

es6 vanilla javascript中的Ajax请求

如何使用 vanilla javascript 通过 ajax 将多张照片上传到 Laravel 应用程序?

没有 jquery 的 Django CSRF 丢失或不正确的 Ajax POST (Vanilla JavaScript)

javascript 使用vanilla JS观察对象属性更改