I have a URL generated by the server. Being in the client I don't know if the URL will be : http://url/parameter
or http://url/parameter?anotherPar=1
.
this value is available to a javascript variable:
var theUrl = '{someURLgeneratedByTheServer}';
I'd like to use window.location.href
passing some parameters, but I can't just do it:
window.location.href = theUrl + '?someClientGeneratedParameter=value&secondParameter=value2';
for this would be invalid if the server-generated URL already has some querystring parameters. I know that when I'm using jQuery's Ajax method I can use the options parameter passing the data object with the needed querystring parameters, and jQuery itself is able to decide wheter it has to concat with ? or &, like this:
$.ajax({
type: "GET",
url: theUrl,
data: {someClientGeneratedParameter:'value', secondParameter:'value2'},
success: callback
});
Is there a way to make a redirection using this concat mechanism of jquery before calling location.href
? (something like below):
//supposition only, when theUrl equals 'http://url/parameter?anotherPar=1'
var finalUrl = $.getMyFinalUrl({url: theUrl,
data: {someClientGeneratedParameter:'value', secondParameter:'value2'}
});
window.location.href = finalUrl ;
Does it make sense or should I write my own method?
Thanks.
PS: using Asp.net MVC3 on the server + C#.
How about something like this? Rip out the demo code and it's very simple and let's you pass parameters by array:
function getURL(theUrl, extraParameters) {
var extraParametersEncoded = $.param(extraParameters);
var seperator = theUrl.indexOf('?') == -1 ? "?" : "&";
return(theUrl + seperator + extraParametersEncoded);
}
// Test1
var theUrl1 = "http://example.com/test"
var extraParameters1 = {
"someClientGeneratedParameter": "value",
"secondParameter": "value2"
};
alert(getURL(theUrl1, extraParameters1));
// Test2
var theUrl2 = "http://example.com/?test=test"
var extraParameters2 = {
"someClientGeneratedParameter": "value",
"secondParameter": "value2"
};
alert(getURL(theUrl2, extraParameters2));
Output:
http://example.com/test?someClientGeneratedParameter=value&secondParameter=value2 http://example.com/?test=test&someClientGeneratedParameter=value&secondParameter=value2
Fiddle: http://jsfiddle.net/gjuqG/