JS如何获取地址栏url后面的参数?

2021-05-13 16:32

阅读:671

标签:ons   location   url   ams   this   博客   tac   oca   evel   

本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:JS如何获取地址栏url后面的参数?;

这里提供了两种获取地址栏url后面参数的方法:

方式1

传参:

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

获取参数:

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;

方式2

传参:

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

获取参数:

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');

参考文章:

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

JS如何获取地址栏url后面的参数?

标签:ons   location   url   ams   this   博客   tac   oca   evel   

原文地址:https://www.cnblogs.com/cobcmw/p/11997693.html


评论


亲,登录后才可以留言!