7

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?

bdz
  • 321
  • 1
  • 6
  • 15

4 Answers4

10

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

Krzysztof Jabłoński
  • 1,890
  • 1
  • 20
  • 29
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0

A simple one if you know the url always has id and name

var url = "www.test.com/index.html?id=1&name=boo";
var id = /id=(\d+)/.exec(url)[1];
var name = /name=(\w+)/.exec(url)[1];
Mifeng
  • 1,525
  • 15
  • 26
0

Here i have done complete solution for above issue. please check demo link as shown below:

For that, you have first include latest jquery.js and querystring-0.9.0.js scripting files in header tag.

Demo: http://codebins.com/bin/4ldqpac

HTML

<a href="#?param1=abc&param2=def">
  abc
</a>

JQuery

$(function() {
    $("a").click(function() {
        setTimeout(function() {
            var param1 = $.QueryString("param1");
            var param2 = $.QueryString("param2");
            alert(param1);
            alert(param2);
        }, 300);

    });
});

Demo: http://codebins.com/bin/4ldqpac

gaurang171
  • 9,032
  • 4
  • 28
  • 30
0

Try this: Working fine in IE and chrome both.Get query string values through javascript

$.urlParam = function(name){
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null){
           return null;
        }
        else {
           return decodeURI(results[1]) || 0;
        }
    }

        var getData= $.urlParam('emailid');
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ashish Pathak
  • 827
  • 8
  • 16