0

Let's say I have am dynamically passing information to a variable in a URL like as shown below:

<script>

var ORDER = 200;
var QUANTITY = 1;
var EXTRA = [200,300,400];

var tag = document.write('<scr'+'ipt language="JavaScript" src="http://test.com/test/order.' + ORDER + '/quantity.' + QUANTITY"></scr' + 'ipt>');

</script>

Let's say I want to pass all the data in the EXTRA array... how would I do this?

I'm trying to get a URL that looks something like this after it is written to the page:

http://test.com/test/order.200/quantity.1/extra.200/extra.300/extra.400

(Passing the numbers to the same extra parameter in the URL is intentional, I need it to be passed in seperate instances but to the same variable)

I know I can use a for loop to cycle through the array.. how can I keep dynamically appending the numbers in the EXTRA array to the URL like in the example above?

Would something like this work?

for (i = 0; i < EXTRA.LENGTH; i++){
   tag.append(EXTRA[i]);
}

Please advise if you can,

Thanks for your help!

Kamui
  • 569
  • 1
  • 7
  • 13
  • Dear friend, I think your problem is a different one. Why don't you use AJAX (eg. jQuery $.get) to send your params and get what you need? – aldux Jul 11 '13 at 20:04
  • Create your string before you pass it to `document.write`, then do normal string concatenation. There's no `.append()` method. –  Jul 11 '13 at 20:04
  • 1
    Tips: 1. http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice, 2. lowercase or cameCase for variables, uppercase represents CONSTANTS. 3. Double-check syntax highlighting in concatenation. 4. Forgot to declare `i`. 5. Encode your URL's. – elclanrs Jul 11 '13 at 20:07
  • In `document.write(............. + QUANTITY + '">');` you missed `+ '` after `QUANTITY` – Givi Jul 11 '13 at 20:10

1 Answers1

5

This looks like a question about joining items in an Array. JavaScript has Array.prototype.join for this purpose, so you would want to do

var str = 'foo';
if (EXTRA.length) str += '/extra.' + EXTRA.join('/extra.');
str; // "foo/extra.200/extra.300/extra.400"
Paul S.
  • 58,277
  • 8
  • 106
  • 120