javascript 如何在javascript函数中将url作为参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10660902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass url as parameter in javascript function?
提问by Vikram
I need to call a javascript function and pass a long url in that. which gives unescaped error because of some special characters. i can't use escape characters because the url is picked dynamically and passed to the function. How can i do this?
我需要调用一个 javascript 函数并在其中传递一个长网址。由于某些特殊字符,这会产生未转义的错误。我不能使用转义字符,因为 url 是动态选择并传递给函数的。我怎样才能做到这一点?
回答by Nefron
回答by Jayaraman M
I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code on Snipplr. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.So as an example if we had the following url with the javascript at the bottom in place.
我需要读取 URL GET 变量并根据 url 参数完成操作。我四处寻找解决方案,并在 Snipplr 上发现了这段代码。它基本上读取当前页面的 url,对 URL 执行一些正则表达式,然后将 url 参数保存在一个关联数组中,我们可以很容易地访问它。例如,如果我们有以下 url 和底部的 javascript。
http://papermashup.com/index.php?id=123&page=home
http://papermashup.com/index.php?id=123&page=home
All we'd need to do to get the parameters id and page are to call this:
获取参数 id 和 page 所需要做的就是调用它:
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}