How to get data from url with jquery

Is it possible to get data from url using jquery

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

how to get id and name?

+4
source share
4 answers

Try it. This is pure javascript, not involved jQuery. Actually jQuery is too heavy for such work.

 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'); 

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

+8
source
 $.urlParam = function(name) { var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); return results[1] || 0; } //example params with spaces http://www.jquery4u.com?city=Gold Coast console.log($.urlParam('city')); //output: Gold%20Coast console.log(decodeURIComponent($.urlParam('city'))); 
+1
source

Simple, if you know that a 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]; 
0
source

Here I made a complete solution for the above problem. check out the demo link as below:

To do this, you first include the jquery.js and querystring-0.9.0.js tags in the 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

0
source

Source: https://habr.com/ru/post/1434568/


All Articles