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

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

问题描述

考虑:

http://example.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 query strings...

推荐答案

使用窗口.位置对象.这段代码为您提供了没有问号的GET.

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的答案,即确实很好,正如他指出的那样,我完全遵循操作员的要求:

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),并且还添加了

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.

否则,使用普通的for循环,即使在IE8中也可以使用:

Or otherwise with plain for loop, 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天全站免登陆