【发布时间】:2012-01-05 09:10:28
【问题描述】:
我想在单击按钮时将用户重定向到目标 URL。目标 URL 是可变的,必须从当前页面 URL 参数“源”中读取:
例如,我有一个网址http://w/_l/R/C.aspx?source=http://www.google.com
当用户点击一个按钮时,他被重定向到http://www.google.com
我将如何使用 jQuery 来做到这一点?
【问题讨论】:
标签: javascript jquery redirect
我想在单击按钮时将用户重定向到目标 URL。目标 URL 是可变的,必须从当前页面 URL 参数“源”中读取:
例如,我有一个网址http://w/_l/R/C.aspx?source=http://www.google.com
当用户点击一个按钮时,他被重定向到http://www.google.com
我将如何使用 jQuery 来做到这一点?
【问题讨论】:
标签: javascript jquery redirect
首先你需要获取 url 参数:source 这可以通过如下函数来完成:
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
【讨论】:
在按钮单击处理程序上,只需编写 window.location.href = http://www.google.com
【讨论】:
您需要解析查询字符串以获取变量源的值。 你不需要 jQuery。
这样一个简单的函数就足够了:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
【讨论】:
使用来自here 的 url 解析代码使用它来解析您的 url(这应该包含在您的文档中一次):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
然后这样做重定向到源参数:
window.location.href = urlParams["source"];
【讨论】:
由于您使用的是 jQuery 框架,我将使用 jQuery URL Parser plugin,它可以安全地解析和解码 URL 参数、片段...
你可以这样使用它:
var source = $.url().param('source');
window.location.href = source;
【讨论】:
获取 url 参数:(从另一个 stackoverflow 问题复制):
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
【讨论】:
你可以这样做,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});
【讨论】: