0

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?

0

2 Answers 2

2

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("&");
Sign up to request clarification or add additional context in comments.

3 Comments

You should mention that map is not available in all browsers... edit: +1 for a more complete solution
@Felix: I realised that right after I hit "Submit". Edited to include the information.
@lonesomeday: That's a good point. @joe, you can wrap name in the escape function to make sure there are no dodgy characters in your query string: return "name=" + escape(name);.
0

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.

2 Comments

He could, but is it worth including the whole library only for using this function?
well, if you just use the library for one page you can include the library only on that page. (and i like using jQuery because it's easier and you don't have to worry too much about browser compatibility)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.