bdz bdz - 2 months ago 17
jQuery Question

how to get data from url with jquery

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?

Answer

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 ?.