如何从JavaScript中检索GET参数? [英] How to retrieve GET parameters from javascript?

查看:85
本文介绍了如何从JavaScript中检索GET参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://domain.com/page.html?returnurl=%2Fadmin

page.html js ,它如何检索 GET 参数?

For js within page.html,how can it retrieve GET parameters?

对于上面的简单示例, func('returnurl')应该是 / admin

For the above simple example,func('returnurl') should be /admin

但它也应该适用于复杂的查询字符串...

But it should also work for complex querystrngs...

推荐答案

使用窗口.location 对象。
$ b

With the window.location object. This code gives you GET without the question mark.

window.location.search.substr(1)

在您的示例中,它将返回 returnurl =%2Fadmin

From your example it will return returnurl=%2Fadmin

编辑:我冒昧地更改 Qwerty的答案 a>,这是非常好,正如他指出的那样,我完全遵循OP的要求:

EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}

我从他的代码中删除了重复的函数执行,将其替换为一个变量(tmp )以及我已经添加了 decodeURIComponent ,正如OP所要求的。我不确定这是否会成为安全问题。

I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.

或者以其他方式使用纯循环,即使在IE8中也是如此:

Or otherwise with plain for cycle, which will work even in IE8:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}

这篇关于如何从JavaScript中检索GET参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆