Reputation: 4963
I have been trying fetching the query string
from url using javascript.
I am using following code
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function() {
prodId = getParameterByName('id');
prodName = getParameterByName('name');
});
It works well for URL like http://my_ip/main.html?id=123&name=test
But when URL is like http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test
it fails, giving empty string for prodID
and prodName
Upvotes: 1
Views: 363
Reputation: 193301
The problem is that http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test
doesn't have location.search
part. It has location.hash
- everything after #
character.
The simple thing you can do is to modify the function to be able to work with location.hash too. For example like this:
function getParameterByName(name, useHash) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location[useHash ? 'hash' : 'search']);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
and then use it like this:
var prodId = getParameterByName('id', true); // true - use location.hash for "query parameters"
Upvotes: 2