문제

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/

다른 팁

A simple expression to check the url before appending data should suffice:

location.href.match(/(\?|&)anotherPar($|&|=)/)

That will tell you if you need to append ? or &.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top