JQuery 获取URL参数

在 jQuery 中,可以使用 window.location.search 属性获取 URL 中的查询参数。该属性返回一个字符串,其中包含 URL 中的查询参数和对应的值。

下面是一个简单的示例,展示如何使用 jQuery 获取 URL 中的参数:

var queryString = window.location.search;
var params = {};

if (queryString) {
  var pairs = queryString.split('&');
  for (var i = 0; i < pairs.length; i++) {
    var pair = pairs[i].split('=');
    params[pair[0]] = pair[1];
  }
}

// 打印查询参数
console.log(params);

上述代码中,window.location.search 获取了 URL 中的查询参数,然后使用 split() 方法将查询参数分割成键值对,并将它们存储在 params 对象中。最后,使用 console.log() 打印出查询参数。

例如,如果 URL 是 http://example.com/?name=John&age=25,则上述代码将输出以下结果:

{ name: 'John', age: '25' }

定义参通用方法
common.js


//根据json中的日期格式,转换成yyyy-mm-dd HH:mm:ss
function DateFormat(cellval) {
    if (cellval == null || cellval == undefined || cellval == 'undefined')
        return '';
    var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
}


function getParam() {
    var queryString = window.location.search;
    var params = {};

    if (queryString) {
        var pairs = queryString.split('&');
        for (var i = 0; i < pairs.length; i++) {
            var pair = pairs[i].split('=');
            if(pair.length>0){
                params[pair[0].replace('?','')] = pair[1];
            }
        }
    }
    return params;
}

URL add.html?id=25465bcb-a9b4-4785-9caf-8ca9561fd61e&name=ABC

<script type="text/javascript">
$(function(){
    if ($.cookie('LoginUser') === undefined) {
        top.location = 'login.html';
    }

    var params = getParam();
    console.log(params);
});
</script>

输出

{
    "id": "25465bcb-a9b4-4785-9caf-8ca9561fd61e",
    "name": "ABC"
}
posted @ 2023-12-28 17:42  VipSoft  阅读(190)  评论(0编辑  收藏  举报