how to get data from url with jquery

前端 未结 4 1191
礼貌的吻别
礼貌的吻别 2021-01-13 01:13

Is it possible to get data from an url with jquery

for example if you have www.test.com/index.html?id=1&name=boo

how to get id and name?

4条回答
  •  时光取名叫无心
    2021-01-13 01:56

    Try this. It's pure javascript, no jQuery involved. In fact jQuery is too heavy for such a job, really.

    function GetURLParameter(sParam)
    {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++)
        {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam)
            {
                return decodeURIComponent(sParameterName[1]);
            }
        }
    }​
    
    var id = GetURLParameter('id');
    var name= GetURLParameter('name');
    

    decodeURIComponent should be used to allow parameter value contain any character, for example the very crucial equals sign =, an ampersand & or a question mark ?.

提交回复
热议问题