0

我对Javascript相当陌生,并组装了以下内容(部分来自在线示例,其余部分由我完成):

这很可靠,我只是想知道我违反了多少最佳实践。如果有人很好地提供有关此脚本后半部分的一般反馈,那将不胜感激。

包含的两个功能是 (1) 在页面上捕获传入网站访问者的推荐数据,包括用于分析的 URL 查询字符串,并将其存储到 cookie。(2) 当访问者完成一个表单时,该脚本将读取 cookie 的 URL 值,将该 URL 解析为段,并将段数据写入表单上预先存在的隐藏输入中。

这将捕获和解析的示例 URL:http ://example.com/page?utm_source=google&utm_medium=abc&utm_campaign=name1&utm_adgroup=name2&utm_kw=example1&kw=example2&mt=a&mkwid=xyz&pcrid=1234

function storeRef() { //this function stores document.referrer to a cookie if the cookie is not already present
    var isnew = readCookie('cookiename'); //set var via read-cookie function's output
        if (isnew == null) {
            var loc=document.referrer; 
            createCookie('cookiename',loc,0,'example.com'); //create cookie via function with name, value, days, domain 
        }
}

function printQuery() { //function to parse cookie value into segments
    var ref=readCookie('cookiename'); //write cookie value to variable
    var refElement = ref.split(/[?&]/); //create array with variable data, separated by & or ?. This is for domain info primarily.
    var queryString = {}; //From http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
    ref.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) { queryString[$1] = $3; } 
    );
//write segments to form field names below.     
    document.getElementsByName('example1')[0].value = refElement[0]; //exampleX is a form hidden input's name. I can not use getElementById here.
//need to be able to manually define these, which is why they aren't in a loop, though I'm not sure how to loop an array referenced in this way
    document.getElementsByName('example2')[0].value = queryString['utm_source']; 
    document.getElementsByName('example3')[0].value = queryString['utm_medium'];
    document.getElementsByName('example4')[0].value = queryString['utm_term'];
    document.getElementsByName('example5')[0].value = queryString['utm_content'];
    document.getElementsByName('example6')[0].value = queryString['utm_campaign'];
    document.getElementsByName('example7')[0].value = queryString['utm_adgroup'];
    document.getElementsByName('example8')[0].value = queryString['utm_kw'];
    document.getElementsByName('example9')[0].value = queryString['kw'];
    document.getElementsByName('example10')[0].value = queryString['mt'];
    document.getElementsByName('example11')[0].value = queryString['mkwid'];
    document.getElementsByName('example12')[0].value = queryString['pcrid'];
}

谢谢!

4

1 回答 1

0

如果除非您想跟踪访问您网站的访问者,为什么您需要使用 cookie 来存储数据?

于 2013-03-14T06:09:25.963 回答