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?
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;
Pass an array of strings as URL parameters:
const myLink = 'https:/example.com/api'
const myArray = ['aaa', 'bbb', 'ccc'];
let apiUrl = `${myLink}/query?`;
myArray.forEach((x) => {
apiUrl += `&array=${x}`;
});
console.log(apiUrl);
// https://example.com/api/query?array="aaa"&array="bbb"&array="ccc"
I'd go with this approach,
var myArray = ['aaa', 'bbb', 'ccc', ];
var myArrayQry = myArray.map(function(el, idx) {
return 'myArray[' + idx + ']=' + el;
}).join('&');
// myArray[0]=aaa&myArray[1]=bbb&myArray[2]=ccc
Then, I retrieve the URL query params as an array on the server side.
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().
try this
$('#myLink').attr({"href" : '/myLink?array=' + myArray.join(',')});
on server: capture and split data.