JavaScript以从URL参数中提取数据填充表单字段
我正在尝试使用JavaScript从URL参数“ UTM_SOURCE”提取数据,并将其添加到表单上的字段中,以便将其存储在我的联系数据库中以进行跟踪。
我以前曾在另一个网站上完成此操作,但是当试图重复使用代码时,它对我不起作用。
该页面在此处(随附要提取的URL参数):
description在我的表单上,在这种情况下,从“ utm_source” URL参数(在这种情况下为'YouTube')填充了值。
这是我使用的代码:
<script type="text/javascript">
function addSource() {
var fieldToChange = document.getElementsByName("form_submission[custom_4]");
var source = trafficSource();
fieldToChange.value = source;
}
var trafficSource = function() {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == "utm_source"){
return pair[1];
} else if (pair[0] == "gclid") {
return 'google';
}
}
return 'unknown';
}
document.onload = addSource();
</script>
I am trying to use javascript to extract data from the URL parameter 'utm_source' and add it to a field on a form so that it is stored in my contact database for tracking purposes.
I had previously accomplished this on another site, but when trying to reuse the code it is not working for me.
The page is here (with the included URL parameter to be extracted):
The desired result if for the 'traffic_source' field on my form to be populated with the value from the 'utm_source' URL parameter, in this case 'youtube'.
Here is the code I am using:
<script type="text/javascript">
function addSource() {
var fieldToChange = document.getElementsByName("form_submission[custom_4]");
var source = trafficSource();
fieldToChange.value = source;
}
var trafficSource = function() {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == "utm_source"){
return pair[1];
} else if (pair[0] == "gclid") {
return 'google';
}
}
return 'unknown';
}
document.onload = addSource();
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
new UrlsearchParams(window.location.search)
进行所有查询参数,并使用searchparams.get('utm_source')获取特定的查询参数
,然后存储utm_source
在表单字段中使用docuct.getElementById(“ utmsource”)。值= param;
。You can take all the query params using
new URLSearchParams(window.location.search)
and get the particular query param usingsearchParams.get('utm_source')
and then, store the value ofutm_source
in form field usingdocument.getElementById("utmsource").value = param;
.fieldTochange
是一个节点符,因此,如果要更改需要指定索引号的值属性,因此这应该修复您的代码
fieldToChange
is a NodeList so if you want to change the value property you need to specify the index numberSo this should fix your code