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?
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
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 "&".
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.
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().
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With