joe
joe

Reputation: 23

Javascript Array

Say I have a bunch of names in a array and I want to post this data to another url on my site, but the post data will be "name="+name+"&name="+name+""; etcetc

So for each name i need to generate another name= to add to post data until there are no more names

How can I do this?

Upvotes: 0

Views: 67

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You can use jquery param() to serialize an array to post it in a url. look here for reference. It's very useful becouse it encodes automatically your data.

Upvotes: 0

Samir Talwar
Samir Talwar

Reputation: 14330

You can map every element in the array to the same thing with name= prepended, and then join them with the & character.

return names.map(function(name) {
    return "name=" + name;
}).join("&");

If you need to support browsers that don't have the map method on Array (it requires JS 1.6), you can pinch it from the MDC or just use a for loop instead.

var queryBits = [];
for (var i = 0, len = names.length; i < len; i++) {
    queryBits.push("name=" + names[i]);
}
return queryBits.join("&");

Upvotes: 2

Related Questions