向URL添加参数,将数组放入查询字符串 [英] Adding parameters to URL, putting array in query string
问题描述
我建立了一个互动,人们可以选择六名球员来组建他们的全明星球队。当他们点击分享到Twitter时,我希望有一个包含所有六个玩家参数的URL,例如 website.com/?playerName=picked?playerName=picked
以便人们可以分享他们的团队
I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked
so that people can share their teams
- 附加参数的最佳方法是什么到一个URL?
- 如何将数组放入查询字符串?
推荐答案
您可以直接在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+'[]=')
}
这篇关于向URL添加参数,将数组放入查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!