无法执行' fetch'在' window':无效的名称

发布于 2025-02-13 18:36:39 字数 1151 浏览 0 评论 0原文

简单的网站使用获取fording formdata与API联系。 fetch方法返回以在“窗口”上执行'fetch':在控制台中的名称“错误”错误,同时xmlhtttprequest作品。 如何修复获取方法?

contactForm.addEventListener('submit', async function (e) {
  e.preventDefault();
  // console.log('clicked');

  const formData = {
    name: formName.value,
    email: formEmail.value,
    tel: formTel.value,
    message: formMessage.value,
  };

  // FIXME
  try {
    const response = await fetch('/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData),
    });

    return response.json();
  } catch (err) {
    console.log(err.message);
  }

  // XMLHttp methode works
  // let xhr = new XMLHttpRequest();
  // xhr.open('POST', '/');
  // xhr.setRequestHeader('Content-Type', 'application/json');
  // xhr.onload = function () {
  //   if (xhr.responseText === 'success') {
  //     //add a popout window

  //     formName.value = '';
  //     formEmail.value = '';
  //     formTel.value = '';
  //     message.value = '';
  //   } else {
  //     alert('Something went wrong!');
  //   }
  // };
  // xhr.send(JSON.stringify(formData));
});

simple website contact submit code using fetch sending formdata to api.
the fetch method returns'Failed to execute 'fetch' on 'Window': Invalid name' error in console, meanwhile XMLHttpRequest works.
How can i fix the fetch method?

contactForm.addEventListener('submit', async function (e) {
  e.preventDefault();
  // console.log('clicked');

  const formData = {
    name: formName.value,
    email: formEmail.value,
    tel: formTel.value,
    message: formMessage.value,
  };

  // FIXME
  try {
    const response = await fetch('/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData),
    });

    return response.json();
  } catch (err) {
    console.log(err.message);
  }

  // XMLHttp methode works
  // let xhr = new XMLHttpRequest();
  // xhr.open('POST', '/');
  // xhr.setRequestHeader('Content-Type', 'application/json');
  // xhr.onload = function () {
  //   if (xhr.responseText === 'success') {
  //     //add a popout window

  //     formName.value = '';
  //     formEmail.value = '';
  //     formTel.value = '';
  //     message.value = '';
  //   } else {
  //     alert('Something went wrong!');
  //   }
  // };
  // xhr.send(JSON.stringify(formData));
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文