I have a simple .htm web page kept in different folders for handling different languages.
default.htm inside en folder (en\default.htm and de\default.htm and so on)
I need to redirect to a specific web page based on the URL parameter i.e. if the user had
specified http://localhost/website/default.htm?lang=de
, i need to redirect him to the
de\default.htm file. i.e. a german web page.
had it been the ASPX pages i would have done away with the job easily with ResourceManager
and an appropriate .resx file using the Request.QueryString option provided by .NET
BCL. However since i'm using plain HTML page i do not have an expertise to write a client
side script like javascript to query for the URL parameters and redirect the user to the
required page.
Question :
Can anyone guide me how do i achieve the same using any form of client scripting to
achieve the redirection ?? And where do i invoke the script function ?
i.e query the parameter for each post event.??
Thanks a ton
You can use javascript to get a list of params pretty easily with the following line.
var paramArray = window.location.search.substring(1).split("&")
This will build an array of the parameters of the query string. From there you just need to add logic to find the param you specified in your question and take the appropriate redirect using
window.location.href = 'some URL'; //causes the browser to refresh with the new URL
Example:
function getQueryStringArray(){
var assoc=[];
var items = window.location.search.substring(1).split('&');
for(var j = 0; j < items.length; j++) {
var a = items[j].split('='); assoc[a[0]] = a[1];
}
return assoc;
}
//point at which you want to determine redirection
var qs = getQueryStringArray();
var url = '';
if (qs.lang !== 'undefined' && qs.lang) {
switch (qs.lang) {
case 'en':
url = 'blah';
break;
case 'de':
url = 'meh';
break;
}
window.location.href = url; //reroute
}
See this on how to parse query string parameters using jQuery How can I get query string values in JavaScript?
Then you can redirect to another page with window.location
Something like this
<script>
$(document).ready(function(){
var p = getParameterByName("lang");
var rootUrl = "yourRootUrl";
var url = rootUrl + p + '/default.htm';
window.location = url;
});
</script>
No jQuery
<script>
(function(){
var p = getParameterByName("lang");
var rootUrl = "yourRootUrl/";
var url = rootUrl + p + '/default.htm';
window.location = url;
}());
</script>
The following should do it for you. Just wrap it in <script></script>
tags.
// Locate "lang=...." in the url using regex;
var a = /[\?&]lang=([^\/&#\?]+)/i.exec(window.location.pathname);
// check if the regex matched
if (a) {
// If so, redirect the user
window.location.href = "http://localhost/website/" + a[1] + "/index.htm";
}
This will save you from having to loop through the url, but it does require a basic understanding of how regexp works.