考虑:

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

对于page.html内的js,它如何检索GET参数?

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

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


当前回答

如果你正在使用AngularJS,你可以使用ngRoute模块使用$routeParams

你必须添加一个模块到你的应用程序

angular.module('myApp', ['ngRoute'])

现在你可以使用service $routeParams:

.controller('AppCtrl', function($routeParams) {
  console.log($routeParams); // JSON object
}

其他回答

如果您不介意使用库而不是自己的实现,请查看https://github.com/jgallen23/querystring。

用窗户。位置的对象。这段代码提供了不带问号的GET。

window.location.search.substr(1)

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

编辑:我擅自改变了Qwerty的答案,这真的很好,正如他指出的那样,我完全按照OP的要求做了:

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的要求。我不确定这是不是安全问题。

或者使用普通的for循环,即使在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;
}

这个函数使用正则表达式,如果参数不存在或没有任何值,则返回null:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

您可以使用位置对象中可用的搜索函数。搜索函数提供URL的参数部分。详细信息可在位置对象中找到。

你将不得不解析结果字符串来获得变量和它们的值,例如在'='上拆分它们。

我这样做(检索一个特定的get-parameter,这里'parameterName'):

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);