使用Javascript提取URL查询字符串

时间:2014-07-06 12:27:40

标签: javascript html

我正在尝试使用Javascript从URL中提取“code”参数。

有谁能告诉我为什么我在下面写的javascript不会在HTML页面上打印查询字符串?

非常感谢您的帮助。

网址:google.com?code=123456789

HTML code:

<html>
<body>

Your code is:
<script>
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
    var code = getUrlVars()["code"];
}
</script>

</body>
</html> 

1 个答案:

答案 0 :(得分:0)

function getUrlVars() {
    var vars = {},  //you need object aka hash not an array
        hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        //you need to decode uri components
        vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
    }
    return vars;

}

//you need to call the function outside of its declaration
var code = getUrlVars()["code"]; 
document.write(code); //immediate write to document
or: console.log(code); //log to console