简体   繁体   中英

How can I grab a URL string inside a directory?

I'm using this code to grab Google's utm_campaign from the URL to insert it in a hidden form field:

    <script type="text/javascript">
    function getQueryVariable(variable) {
       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] == variable) {
         return pair[1];
       }
     }
   }
   function onLoad() {
      var value = getQueryVariable("utm_campaign");
      var e = document.getElementById('keyword');
      e.value = value;
   }
   </script>

The code works great in the root URL but when I use it inside a subdirectory it stops working.

site.com/?utm_campaign=test - Works

site.com/directory/?utm_campaign=test - Does not work

How can I grab a URL string inside a directory?

Thanks!

That code should function exactly the same whether you are on the root url or in a subdirectory.

In your case (based on the example lined in your comment), it appears that the onLoad function is only getting run on your root url because the body tag is defined as <body onload="onLoad()">

In order to have the onLoad function executed on your subdirectory pages, you'll need to include onload="onLoad()" in your body tag on those pages as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM