Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array as a URL parameter?

I would like to pass an array and added to a link on my page as a URL parameter, because later on the server side I need the values from the array. How should I do that?

myArray = ['aaa', 'bbb', 'ccc'];  $('#myLink').attr({"href" : '/myLink?array=' + myArray}); 

I am not sure if that is the proper way of doing this?

like image 855
Leff Avatar asked Nov 08 '16 17:11

Leff


People also ask

Can you pass an array as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

How do I pass parameters to URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

Can we pass array in query string Javascript?

We can also pass an array with tuples or a query string. With that done, we now have an instance of the URLSearchParams class. We can get the string version of this by calling toString and append this to our URL.


2 Answers

You can serialize the JSON:

myArray = ['aaa', 'bbb', 'ccc']; var arrStr = encodeURIComponent(JSON.stringify(myArray)); $('#myLink').attr({ href: '/myLink?array=' + arrStr }); 

If your parsing (on the next page) is done via JavaScript too, you'll conversely use JSON.parse(). In PHP it would be json_decode().

like image 140
rodrigocfd Avatar answered Sep 19 '22 13:09

rodrigocfd


It should not depend on the server side: By the URI standard specification, all parameters must have one name and should have one value. But there can be several parameters with the same name, which is the right way to serialize an array:

http://server/context?array=aaa&array=bbb&array=ccc&otherparameter=x

You could do it like this:

var s=""; for (var i=0;i< myArray.length;i++) {   s+="&myArray="+myArray[i]; } var url="http://server/context?"+s; 
like image 37
Little Santi Avatar answered Sep 21 '22 13:09

Little Santi