Reputation: 13
I'm building an interface that uses AJAX with an HTML fallback. I'm setting up all my <a>
tags to work without AJAX first, and if Javascript is enabled, each link will have an "onclick" function attached to it that sends the same exact query string to a different page on my server.
My original link will look like this:
<a class="ajax" href="http://example.com/page?key1=value1&key2=value2">Link</a>
How do I retrieve "key1=value1&key2=value2" as a string from the above href link via Javascript? I will be making AJAX requests that look like http://example.com/ajax?key1=value1&key2=value2
.
Upvotes: 1
Views: 4832
Reputation: 31939
Looking at your comments on other answers, this is what you need
linkElement.search.substr(1)
You can access the same properties you would with window.location
.
For querystring of a href it would be (document.querySelector('a#mylink')).search
.hash
.host
.hostname
.href
.origin
.pathname
.port
.protocol
.search
*I am only selecting links with actual hrefs.
[].forEach.call(document.querySelectorAll('a[href]'), function(el) {
var queryString = el.search.substr(1)
el.onclick = function(e){
e.preventDefault() // don't redirect and stuff...
// do the magic here with the queryString
}
})
Upvotes: 1
Reputation: 2114
This sample code should be enough to help you parse what you need. Note that I added an id to the anchor to make it easy to access.
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function parse() {
var el = document.getElementById("foo");
var href = el.href;
var pos = href.indexOf("?");
alert(href.substring(pos+1));
}
</SCRIPT>
</HEAD>
<BODY bgcolor="white" onLoad="parse()">
<a id="foo" class="ajax" href="http://example.com/page?key1=value1&key2=value2">Link</a>
</BODY>
</HTML>
Upvotes: 0
Reputation: 1074218
You can attach a click
handler either to individual links:
var links = document.getElementsByTagName('a');
var index;
for (index = 0; index < links.length; ++index) {
links.onclick = linkClickHandler;
}
function linkClickHandler() {
var x = this.href.indexOf('?');
var query = x >= 0 ? this.href.substring(x + 1) : null;
if (query) {
// Do the ajax thing...
// (your code here)
// ...and prevent the link from being followed
return false;
}
}
...or (and this is probably better) to document
itself:
document.onclick = function(e) {
var target, x, query;
e = e || window.event;
target = e.target;
if (target.tagName.toUpperCase() === "A") {
x = target.indexOf('?');
query = x >= 0 ? target.substring(x + 1) : null;
if (query) {
// Do the ajax thing...
// (your code here)
// ...and prevent the link from being followed
return false;
}
}
};
In either case, on modern browsers you might want to use addEventListener
rather than onclick
, and call preventDefault
on the event object. But IE8 still uses attachEvent
rather than addEventListener
.
(return false;
from an old-fashioned DOM0 event handler like onclick
prevents the default action of the event; details.)
Upvotes: 1