【发布时间】: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
【问题讨论】: