我对Javascript很新,并汇总了以下内容(部分内容来自在线示例,其余部分来自我):
这是可靠的,我只是想知道我违反了多少最佳实践。如果某人足够好以提供有关此脚本后半部分的一般反馈,那将不胜感激。
这两个包含的功能是(1)捕获页面上传入的网站访问者的推荐数据,包括用于分析的URL查询字符串,并将其存储到cookie中。 (2)当访问者填写表单时,脚本将读取cookie的URL值,将此URL解析为段,并将段数据写入表单上预先存在的隐藏输入。
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'];
}
谢谢!
答案 0 :(得分:0)
为什么您需要使用cookie来存储数据,除非您想跟踪访问您网站的访问者?