How you view and display parameters in jQuery

Suppose you have a URL, for example http://www.somesite.com/somepage.html?id=1&page=2&field=3

Now with jQuery, I would like to display all the GET variables passed to the page. How can I do it? Its fine (perhaps even better) if it is executed as part of some Debug function.

+4
source share
3 answers

You need to look at the window.location.href variable.

Here is a good guide that does exactly what you want: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

Basically extend jQuery with getUrlVars:

 $.extend({ getUrlVars: function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }, getUrlVar: function(name){ return $.getUrlVars()[name]; } }); 

Then use it:

 var allVars = $.getUrlVars(); var byName = $.getUrlVar('name'); 
+1
source
 (function(){ var $_GET = {}; jQuery.each( document.location.search.substr(1).split( "&" ), function(index, value ){ var split = value.split("="); $_GET[decodeURIComponent( split[0] )] = decodeURIComponent( split[1] ); }); window.$_GET = $_GET; })(); 
+2
source

You can use window.location.search . Here is a quick function that will return the parameters as an object:

 function getParameters() { var parameters = {}; var splitStr = window.location.search.substring(1).split(/[&=]/); var i, key, value; for(i = 0; typeof (key = splitStr[i], value = splitStr[i + 1]) !== 'undefined'); i += 2) { parameters[decodeURIComponent(key)] = decodeURIComponent(value); } return parameters; } 
+1
source

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


All Articles