如何将数据层值发送到第3方API端点?

问题描述 投票:0回答:1

我正在尝试捕获表单输入字段值,并在表单提交时使用 Google 跟踪代码管理器将它们发送到第 3 方 API 端点。

到目前为止我做了什么:
我设法定义数据层变量,以便在提交表单后我可以在数据层中看到所需的表单字段输入。在预览模式下,它看起来像这样:

dataLayer.push({event: "gtm.formSubmit", ...})



我还缺少什么?
现在这些值位于数据层中,我需要将它们发送到 REST API 端点。

如何使用自定义 HTML 标签实现此目的?

javascript google-tag-manager
1个回答
0
投票

您可以创建一个自定义 html 标签并将代码放在下面。

但是你需要修改其中的某些部分。

<script>
(function(){
    try {
        var dlvEmail = {{dlv - contact form email}}; 
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Regular expression for basic email validation

        if (dlvEmail && emailRegex.test(dlvEmail)) {
            var xhr = new XMLHttpRequest();
            var endpoint = 'https://example.com/api';
            // modify to the API endpoint you need

            xhr.open('POST', endpoint, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify({ key: dlvEmail }));
            // change the key to the API document need.
        } else {
            console.error('Invalid email format');
        }
    } catch (error) {
        console.error('An error occurred during the request:', error);
    }
})();
</script>

如果一切正常,您可以测试它。您可以删除代码中的console.log以确保不会中断控制台。

如果API文档需要一些额外的授权。

修改代码或者查看xhr如何实现auth即可。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.