How to get JS parameters behind the address bar url?

This article is no longer updated, there may be instances of outdated content, real-time updates please move to my new blog: How to get parameters behind JS address bar url? ;

Here are two ways to get behind the address bar url parameter:

Mode 1

Parameter passing:

window.location.href = "/html/bsp/user/userEdit.html?name=四个空格&age=2";

Acquisition parameters:

function getParams() {
    var params = {};
    if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
        var paramArray = unescape(this.location.search).substring(1, this.location.search.length).split("&");
        if (paramArray.length > 0) {
            paramArray.forEach(function (currentValue) {
                params[currentValue.split("=")[0]] = currentValue.split("=")[1];
            });
        }
    }
    return params;
}

var name = getParams().name;

Mode 2

Parameter passing:

var params = {};
params['name'] = '四个空格';
params['age'] = '2';
window.location.href = "/html/bsp/user/userEdit.html?" + new URLSearchParams(params);

Acquisition parameters:

function urlParams(){
    var searchParams;
    if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
        searchParams = new URLSearchParams(this.location.search.substring(1, this.location.search.length));
    }
    return searchParams;
}

var name = urlParams().get('name');

Reference article:

  1. URLSearchParams
  2. Is there any native function to convert json to url parameters?

Guess you like

Origin www.cnblogs.com/cobcmw/p/11997693.html