无法将cookie值写入表单字段

时间:2013-10-16 14:46:46

标签: javascript html cookies google-adwords

成为Javascript新手我在使用Google的Adwords GCLID跟踪功能时遇到了一些问题。我正在关注他们的代码示例https://support.google.com/adwords/answer/2998031

您可以看到存储的Cookie,但在尝试检索它并填充隐藏的表单字段时,结果只是空白。我使用了其他变体,但这只会导致“未定义”作为字段值。

这是我正在使用的代码

简化的HTML表单

<form class="signup-form" name="signupform" method="post" action="step2.php">
    <input type="hidden" name="gclid" id="gclid" value="" />
</form>

Cookie写脚本

<script type="text/javascript">
    function setCookie(a,d,b){var c=new Date;c.setTime(c.getTime()+864E5*b);b=";
    expires="+c.toGMTString();document.cookie=a+"="+d+b}function getParam(a)     {return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))}var gclid=getParam("gclid");if(gclid){var gclsrc=getParam("gclsrc");(!gclsrc||-1!==gclsrc.indexOf("aw"))&&setCookie("gclid",gclid,90)};
</script>

Cookie阅读脚本

<script> 
  function readCookie(name) { 
      var n = name + "="; 
      var cookie = document.cookie.split(';'); 
      for(var i=0;i < cookie.length;i++) {      
          var c = cookie[i];      
          while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
          }      
          if (c.indexOf(n) == 0){
            return c.substring(n.length,c.length);
          } 
      } 
      return null; 
  } 

  function() {      
      document.getElementById('gclid').value = readCookie('gclid'); 
  } 
</script>

2 个答案:

答案 0 :(得分:1)

function() {      
    document.getElementById('gclid').value = readCookie('gclid'); 
} 

这是一个没有永远不会被调用的名字的函数。尝试仅用

替换它
document.getElementById('gclid').value = readCookie('gclid'); 

我重写了你的写脚本,我认为你的cookie永远不会被设置。

function setCookie(a,d,b) {
    var c = new Date;
    c.setTime(c.getTime()+864E5*b);
    b="; expires=" + c.toGMTString();
    document.cookie = a + "=" + d + b
}

function getParam(a) {
    return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))
}

var gclid=getParam("gclid");

if(gclid) {
    var gclsrc = getParam("gclsrc");
    if(!gclsrc||-1 !== gclsrc.indexOf("aw")) {
        setCookie("gclid", gclid, 90);
        alert("Cookie Set!");
    }
}

答案 1 :(得分:0)

https://support.google.com/adwords/answer/3285060修改的工作脚本。我刚刚将document.onload更改为window.onload看起来在DOM的屏幕上发生了太多的事情。

<script> 
 window.onload = function getGclid() {        
   document.getElementById("gclid").value = (name = new    
 RegExp('(?:^|;\\s*)gclid=([^;]*)').exec(document.cookie)) ? 
 name.split(",")[1] : ""; } 
</script>