Function To Retrieve Url Variables Using Javascript And Jquery?
in my script there a simple list shows links for editing
- click here
- (i.e. the URL within your brother). Just modify the first method like this to make it work:
$(function() { functiongetUrlVars(url) { var vars = [], hash; var hashes = url.slice(url.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; } $('.edit').click(function() { var href = $(this).attr("href"); var test = getUrlVars(href)["id"]; alert(test); }); });
Side note: you could also modify the second one, both of them do the same job.
Solution 2:
You could try this:
JavScript
functiongetUrlParams() {
var params = {};
location.search.replace(/\?/g, '').split('&').forEach(function(item) {
params[item.split('=')[0]] = item.split('=')[1];
});
return params;
}
The function will return an object like this:
{
firstName: 'Jordan',
lastName: 'Belfort',
position: 'The Wolf of Wall Street',
}
Usage
var urlParams = getUrlParams();
alert('Hello ' + urlParams.firstName + ' ' + urlParams.lastName);
Note: There's actually no need to use location.href and split the url at '?', since we can get the whole query string with location.search
.
Solution 3:
As an alternative to your problem, why not put the id
part of the href
into a data
parameter and read that? It would save you having to dissect the URL. Try this:
<ul><li><ahref="edit.php?id=5"data-id="5"class="edit">click here</a></li><li><ahref="edit.php?id=6"data-id="6"class="edit">click here</a></li><li><ahref="edit.php?id=7"data-id="7"class="edit">click here</a></li><li><ahref="edit.php?id=8"data-id="8"class="edit">click here</a></li></ul>
$('.edit').click(function(){
var id = $(this).data("id");
alert(id);
});
Solution 4:
Try this one:
functiongetParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = newRegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return"";
elsereturndecodeURIComponent(results[1].replace(/\+/g, " "));
}
Solution 5:
You almost got it right the first time, you just have to declare vars
as object and get rid of vars.push(...)
.
Here's working example - http://jsfiddle.net/KN9aK/1/show/?id=yoursuperduperid
Source here http://jsfiddle.net/KN9aK/1/
Post a Comment for "Function To Retrieve Url Variables Using Javascript And Jquery?"