meddiecap Posted November 7, 2009 Share Posted November 7, 2009 Hi,I'm working on a script where I need to send a query string to another page.This query string however is made up with several values that are added to the string conditionally.In PHP for example you can continue with variables like so:$var .= 'value';$var .= 'value2';echo $var; // result valuevalu2How does this work with javascript? var Number = Number + 'whatever'; (?)Or does it have a similar method as in PHP?(A link where this is explained will suffice)Thank you. Link to comment Share on other sites More sharing options...
chibineku Posted November 7, 2009 Share Posted November 7, 2009 You can use the + symbol to concatenate or += in the same fasion as .= Link to comment Share on other sites More sharing options...
jeffman Posted November 7, 2009 Share Posted November 7, 2009 The plus ( + ) sign is both an addition operator and a concatenation operator. So combining strings is as simple as the following:var myKey = "name";var myVal = "Bob";var myQuery = myKey + "=" + myVal;// returns "name=Bob"The increment operator works also:myQuery += "&city=townsville"; // returns "name=Bob&city=townsville"But be wary. If you try to add numbers that still exist as strings (as when they come out of text inputs), they will not automatically be cast as numbers. You'll have to cast them yourself or force them to be cast:var i = 1;var s = "1";var result = i + s;// returns "11";result = i + Number(s);// returns 2result = i + (s * 1);// returns 2 Link to comment Share on other sites More sharing options...
meddiecap Posted November 7, 2009 Author Share Posted November 7, 2009 Using += like this:var querystring += '&nPaginaKL='+nPaginaKL+'&nPaginaZW='+nPaginaZW+'&nPaginaZWatKL='+nPaginaZWatKL;gives me an 'invalid variable initialization'-error??Edit:Got it now.I can't start with +=. I have to do var querysting = 'some value'. Then:querystring += 'somevalue'; Link to comment Share on other sites More sharing options...
Ingolme Posted November 7, 2009 Share Posted November 7, 2009 You need to assign something to your variable before concatenating to it. The way you're doing it, you're trying to append something to nothing, because querystring needs to be declared first. var querystring = '';querystring += '&nPaginaKL='+nPaginaKL+'&nPaginaZW='+nPaginaZW+'&nPaginaZWatKL='+nPaginaZWatKL; Alternatively, there's the String.concat() method: var querystring = new String();querystring.concat('&nPaginaKL=', nPaginaKL, '&nPaginaZW=', nPaginaZW, '&nPaginaZWatKL=', nPaginaZWatKL); Link to comment Share on other sites More sharing options...
jeffman Posted November 7, 2009 Share Posted November 7, 2009 Sorry. I meant to highlight the traps. Forgot that one. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.