JS 获取链接中的参数

Keep Open and Learning
Post Reply
星际浪子
Posts: 3597
Joined: 01 May 2009 23:45

JS 获取链接中的参数

Post by 星际浪子 » 26 Jan 2022 01:37

1、获取链接全部参数,以对象的形式返回


Code: Select all

//获取url中参数
function GetRequest()
 {
    var url = location.search;   //获取url中"?"符后的字串   
    var theRequest = new Object();
    if (url.indexOf("?") != -1) 
    {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) 
        {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
 }
2、根据参数名获取链接中的参数值

Code: Select all

function GetRequest2(key)
 {
    var url = location.search;  
    var theRequest = new Object();
    if (url.indexOf("?") != -1) 
    {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) 
        {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    var value = theRequest[key];
    return value;
 }

Post Reply