所以我有点问题,我正在努力解决这个问题,而且我只做了不到一年的开发,所以事情对我来说还是很新鲜的。我的目标是创建一个脚本,如果它们存在,它能够在url中找到utm值,然后将它们存储到变量中(如果存在的话)。我已经有了一个脚本工作,但只有在网址以非常具体的方式构建时才有效,
本地主机/ utm_source = Google的安培; utm_medium = CPC&安培; utm_campaign =(ROI)+ CDN +一般&安培;的utm_content = CDN +(短语+%26 +宽)及utm_term = CDN&安培; GCLID = CNaV2vnZl7wCFY57QgodbgwA7A
它可能是实际生产中的各种网址,例如 -
本地主机/ utm_source = Google的安培; utm_medium = CPC&安培; utm_campaign =(ROI)+ CDN +一般 本地主机/ utm_source =谷歌&安培; utm_medium = CPC&安培; utm_campaign =(ROI)+ CDN +一般&安培;的utm_content = CDN +(短语+%26 +宽)及utm_term = CDN
这是我到目前为止编写的代码。如果您对如何在任何情况下更好地工作,或者您建议“高级初学者”使用的任何资源有任何建议,我将非常感激!
var urlSearch = window.location.search;
if (urlSearch.length > 1) {
if (urlSearch.match('utm_source=(.*)&utm_medium')) {
var utmSource = urlSearch.match('utm_source=(.*)&utm_medium')[1];
}
if (urlSearch.match('utm_medium=(.*)&utm_campaign')) {
var utmMedium = urlSearch.match('utm_medium=(.*)&utm_campaign')[1];
}
if (urlSearch.match('utm_campaign=(.*)&utm_content')) {
var utmCampaign = urlSearch.match('utm_campaign=(.*)&utm_content')[1];
}
if (urlSearch.match('utm_content=(.*)&utm_term')) {
var utmContent = urlSearch.match('utm_content=(.*)&utm_term')[1];
}
if (urlSearch.match('utm_term=(.*)&')) {
var utmTerm = urlSearch.match('utm_term=(.*)&')[1];
}
}
答案 0 :(得分:0)
您的方法的具体问题是查询字符串不保证按特定顺序排列。因此,如果浏览器或上一页中的任何更改导致查询字符串变量以不同的顺序提交,则代码将停止工作。还有一些其他问题,其中一个问题是解码任何空格或复杂的值。
使用查询字符串解析器,如下例所示:
<title>JavaScript Form Processor</title>
<script>
function ptq(q)
{
/* parse the query */
/* semicolons are nonstandard but we accept them */
var x = q.replace(/;/g, '&').split('&'), i, name, t;
/* q changes from string version of query to object */
for (q={}, i=0; i<x.length; i++)
{
t = x[i].split('=', 2);
name = unescape(t[0]); /* unescape can and should be replaced with decodeURIComponent() for almost all browsers */
if (!q[name])
q[name] = [];
if (t.length > 1)
{
q[name][q[name].length] = unescape(t[1]);
}
/* next two lines are nonstandard */
else
q[name][q[name].length] = true;
}
return q;
}
function param() {
return ptq(location.search.substring(1).replace(/\+/g, ' '));
}
q = param();
firstname = q.name1;
/* use q['name1'] syntax to access more complicated variables from the query string */
document.write('<h1>Hello ', firstname || 'Anonymous', '!</h1>');
</script>
<form>
Type your first name: <input type="text" name="name1" />
<input type="submit" value="Submit" />
</form>
为了解析您在问题中提到的变量,您只需使用上述脚本中创建的q
变量,并访问其属性:
var utmSource = q.utm_source, utmMedium = q.utm_medium, etc.;