dqyat62284 2014-03-20 20:36 采纳率: 0%
浏览 42

在javascript中获取url字符串参数并将它们传递给新的url

I'm trying to use javascript to complete something that i've done a ton of times in PHP.

I have two instances of urls that come into my site. One from a tracking link... and another from search or share, so on...

tracking link: www.foo.com/blog?offer=pine&sub_id=123 non paid search link: www.foo.com/blog

I'd like to detect if my link has a string, and if so pass the offer into a url within the page. In PHP i'd do this like so.

<?php
    if(array_key_exists('sub_id', $array)) {
        $my_variable = $array['sub_id'];
    } else {
        $my_variable = 'my default value';
    }
?>
    <a class="submitbutton" href="www.joinmywebsite.com/join?offer=pine&sub_id=<?php echo $my_variable; ?>">Join My Site</a>

Is it possible to do this with javascript? I've search and search and ever function I find either returns the value of the string parameter or it sees nothing and does nothing.

Thanks.

  • 写回答

2条回答 默认 最新

  • dongshan1036 2014-03-20 20:40
    关注

    Sure:

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(
                                                    results[1].replace(/\+/g, " "));
    }
    
    var subId = getParameterByName('sub_id') || 'my default value';
    
    $(function(){
    
         $('a.submitbutton')
           .prop({ href: 'www.joinmywebsite.com/join?offer=pine&sub_id=' + subId  });
    });
    

    Source: How can I get query string values in JavaScript?

    评论

报告相同问题?