且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向URL添加参数,将数组放入查询字符串

更新时间:2023-02-25 17:21:13

您可以直接在url中使用数组,但是您需要将数组序列化为字符串。像这样播放器[] =一个&播放器[] =两个

You can use an array directly in a url, however you would need to serialize the array into a string. like this player[]=one&player[]=two

这里有一个自动化它的小功能。

here is a little function to automate it.

使用url时,你应该总是使用 encodeURIComponent 来编码任何非url友好字符。玩家是一个数组,所以我们映射它并获得一个已经编码的新数组。

when using url's you should always use encodeURIComponent to encode any non url friendly characters. The players are an array so we map over it and get a new array that has been encoded.

之后我们只需要加入数组&

After that we simply need to join the array with &

const players = [
  'player Name 1',
  'playerName2',
  'playerName3'
]

const parameterizeArray = (key, arr) => {
  arr = arr.map(encodeURIComponent)
  return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}

console.log(parameterizeArray('player', players))

唯一的区别是函数声明样式,其他一切都是标准的ES5

The only difference is the function declaration style, everything else is standard ES5

function parameterizeArray(key, arr) {
  arr = arr.map(encodeURIComponent)
  return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}