Home > Mobile >  Pushing array into JS GET request using spread
Pushing array into JS GET request using spread

Time:01-01

I’m trying to pass an array to a php script as part of an Ajax call. Whilst POST might be simple, it seems GET is the right technique to do this, I’m also making the api code so it can be either way that I send to it. Therefore I want to put the array contents into the url as 2 separate parameters of the request.

After a bit of reading about loops I found the suggestion of using “spread”: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

However I’m not clear how to use it properly. This was my code:

const arg = ['p0', 'p1'];
callMe(arg);

function callMe(…arg){
// ajax GET request
   let url = `api.php?p0=${1}&p1=${2}`;
   // rest of code…
   console.log(arg);
}

This still prints out as an array. How should I be using spread to get p0, p1 put into a url from an array?

CodePudding user response:

You're actually using the rest syntax, which is how you let a function have an infinite number of arguments which will be presented as an array of arguments.

function foo(...args) {
   console.log(args);
}

foo('hello', 1, 'bar', true);

But what you're looking for is to use the spread syntax when passing the args to the callMe function.

See the example below. Here we expect two parameters p0 and p1. When using the spread syntax we pass each item in the array as an argument to the callMe function.

const args = ['foo', 'bar'];

function callMe(p0, p1){
   let url = `api.php?p0=${p0}&p1=${p1}`;
   console.log(url);
}

callMe(...args); // Same as callMe(args[0], args[1]);

  • Related