我有这样的网址:
http://localhost/PMApp/temp.htm?ProjectID=462
我需要做的是获取?符号(查询字符串)之后的详细信息- 即ProjectID=462. 我怎样才能使用 JavaScript 获得它?
到目前为止我所做的是:
var url = window.location.toString();
url.match(?);
我不知道接下来要做什么。
我有这样的网址:
http://localhost/PMApp/temp.htm?ProjectID=462
我需要做的是获取?符号(查询字符串)之后的详细信息- 即ProjectID=462. 我怎样才能使用 JavaScript 获得它?
到目前为止我所做的是:
var url = window.location.toString();
url.match(?);
我不知道接下来要做什么。
看一看的MDN文章有关window.location。
QueryString 在window.location.search.
如果您想要一个更方便的界面来使用,您可以使用searchParamsURL 界面的属性,它返回一个URLSearchParams对象。返回的对象有许多方便的方法,包括 get 方法。所以上面例子的等价物是:
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
该URLSearchParams接口也可以用于在查询字符串格式解析字符串,并把它们变成一个方便URLSearchParams对象。
let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);
searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true
URLSearchParams 接口现在在浏览器中被广泛采用(根据Can I Use 95%+ ),但如果你确实需要支持旧浏览器,你可以使用polyfill。
使用window.location.search后得到的一切? ,包括?
例子:
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})
如果你碰巧使用了Typescript并且在你的lib中有dom,你可以这样做:
tsconfig.json
const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');
// To append, you can also leverage api to avoid the `?` check 
params.append('newKey', 'newValue');
这将添加一个全局函数来访问 queryString 变量作为映射。
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
    window.location.query = function (source) {
        var map = {};
        source = source || this.search;
        if ("" != source) {
            var groups = source, i;
            if (groups.indexOf("?") == 0) {
                groups = groups.substr(1);
            }
            groups = groups.split("&");
            for (i in groups) {
                source = groups[i].split("=",
                    // For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
                    (groups[i].slice(-1) !== "=") + 1
                );
                // Key
                i = decodeURIComponent(source[0]);
                // Value
                source = source[1];
                source = typeof source === "undefined"
                    ? source
                    : decodeURIComponent(source);
                // Save Duplicate Key
                if (i in map) {
                    if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
                        map[i] = [map[i]];
                    }
                    map[i].push(source);
                }
                // Save New Key
                else {
                    map[i] = source;
                }
            }
        }
        return map;
    }
    window.location.query.makeString = function (source, addQuestionMark) {
        var str = "", i, ii, key;
        if (typeof source == "boolean") {
            addQuestionMark = source;
            source = undefined;
        }
        if (source == undefined) {
            str = window.location.search;
        }
        else {
            for (i in source) {
                key = "&" + encodeURIComponent(i);
                if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
                    str += key + addUndefindedValue(source[i]);
                }
                else {
                    for (ii = 0; ii < source[i].length; ii++) {
                        str += key + addUndefindedValue(source[i][ii]);
                    }
                }
            }
        }
        return (addQuestionMark === false ? "" : "?") + str.substr(1);
    }
    function addUndefindedValue(source) {
        return typeof source === "undefined"
            ? ""
            : "=" + encodeURIComponent(source);
    }
}
享受。