首页 > 解决方案 > 纯 JavaScript 中的 XMLhttpRequest

问题描述

我尝试为 hubspot 创建一个自定义表单。我的 HTML 如下所示:

<form id="newsletterForm">
     <input type="text" id="firstname" name="firstname" placeholder="Voornaam">
     <input type="text" id="email" name="email" placeholder="E-mail adres">
     <input type="submit" value="Houd mij op de hoogte!">
     <input type="checkbox" id="privacy" name="privacy" value="false">
     <label for="privacy">Ja, Ik ga akkoord met privacy voorwaarden.*</label><br>
</form> 

我的 JavaScript 看起来像这样:

<script>
window.addEventListener( "load", function () {

  const form = document.getElementById( "newsletterForm" );

  form.addEventListener( "submit", function ( event ) {

          const XHR = new XMLHttpRequest();
    XHR.addEventListener( "load", function(event) {
      alert( event.target.responseText );
    } );

    // Define what happens in case of error
    XHR.addEventListener( "error", function( event ) {
      alert( 'Oops! Something went wrong.' );
    } );

    // Set up our request
    XHR.open( "POST", "https://api.hsforms.com/submissions/v3/integration/submit/:portalId/:formGuid" );
    XHR.setRequestHeader("Content-Type", "application/json");
    XHR.setRequestHeader("Accept", "application/json");
    // The data sent is what the user provided in the form
    XHR.send({
  "fields": [
    {
      "name": "email",
      "value": "ingejoppe@gmail.com"
    },
    {
      "name": "firstname",
      "value": "INge TEST"
    }
  ],
  "legalConsentOptions": {
    "consent": {
      "consentToProcess": true,
      "text": "I agree to allow Example Company to store and process my personal data.",
      "communications": [
        {
          "value": true,
          "subscriptionTypeId": 999,
          "text": "I agree to receive marketing communications from Example Company."
        }
      ]
    }
  }
});
    
  } );
} );

  </script>

当我单击提交时,我巧妙地结束了正确的功能,只有 XMLhttpRequest 没有执行。页面已重新加载,但未发送数据。有什么我想念的吗?我尝试使用 XHR.Send () 将对象作为 JSON.stringify () 发送,但这也无济于事。

在 POST url 中,我使用了正确的值。我可以通过具有相同内容的直接 POST 请求成功执行该操作。

简而言之,我是否忽略了什么?或者我是否需要一个 AJAX 库才能在纯 JavaScript 中用于 XMLhttpRequest

标签: javascriptxmlhttprequest

解决方案


页面已重新加载

这就是提交表单的作用。并且该导航取消了JS。

您需要防止提交事件的默认行为。

event.preventDefault()


旁白:如果您想发布 JSON,那么您传递给的值send()需要是 JSON 而不是对象。


推荐阅读