简体   繁体   English

Javascript-使用哈希获取url参数

[英]Javascript - get url parameter with hash

I try to get the URL parameter ReturnUrl which contains a hash: 我尝试获取包含哈希值的URL参数ReturnUrl

http://localhost/Site?ReturnUrl=%2fPlace#/get

I use the code from How can I get query string values in JavaScript? 我使用“ 如何在JavaScript中获取查询字符串值”中的代码

but it returns only %2fPlace . 但它仅返回%2fPlace Why ? 为什么呢

While location.search + location.hash will return ?ReturnUrl=%2fPlace#/get technically #/get is not part of the ReturnUrl parameter, it is interpreted by the browser as the fragment of the current url. 虽然location.search + location.hash将返回?ReturnUrl=%2fPlace#/get技术上讲#/get不是ReturnUrl参数的一部分,但浏览器将其解释为当前URL的片段。

To handle this more correctly you should be url encoding the # as %23 so the url would be http://localhost/Site?ReturnUrl=%2fPlace%23%2fget 为了更正确地处理此问题,您应该将#编码为%23以使URL为http://localhost/Site?ReturnUrl=%2fPlace%23%2fget

Your problem is in the 您的问题出在

"=([^&#]*)" 

regex tag. 正则表达式标签。 Remove the hash tag, and add "location.hash" to your regex search and you should be set. 删除哈希标签,然后将“ location.hash”添加到正则表达式搜索中,您将被设置。

<script type="text/javascript">
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&]*)"),
        results = regex.exec(location.search + location.hash);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var ReturnUrl = getParameterByName('ReturnUrl');
document.write(ReturnUrl);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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