优米格
分享有营养的

JS中获取地址栏url后面的参数的三种方法

BraUndress.png

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

方式1

传参:

window.location.href = "/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 = "/html/bsp/user/userEdit.html?" + new URLSearchParams(params);

获取参数:

function urlParams() {
    var paramsJson = {};
    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));
        searchParams.forEach(function (value, key, searchParams) {
            paramsJson[key] = value;
        });
    }
    return paramsJson;
}

var urlParamsJson = urlParams();
var name = urlParamsJson.name;

方式3

传参:

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

获取参数:

(function ($) {
    /**
     *    获取地址栏指定参数,添加jQuery扩展
     * */
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

})(jQuery);

var name = $.getUrlParam('name');

参考文章:

  1. URLSearchParams
  2. Is there any native function to convert json to url parameters?
赞(1)
未经允许禁止转载:优米格 » JS中获取地址栏url后面的参数的三种方法

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系