【问题标题】:XMLhttpRequest in plain javascript纯 JavaScript 中的 XMLhttpRequest
【发布时间】:2020-12-21 14:02:04
【问题描述】:

我尝试为 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

【问题讨论】:

    标签: javascript xmlhttprequest


    【解决方案1】:

    页面重新加载

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

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

    event.preventDefault()


    另外:如果您想发布 JSON,那么您传递给 send() 的值必须是 JSON 而不是对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多