简体   繁体   English

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

[英]Adding parameters to URL, putting array in query string

Objective客观的

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当他们点击分享到 Twitter 时,我希望有一个 URL 包含所有六名球员的参数,比如website.com/?playerName=picked?playerName=picked这样人们就可以分享他们的球队

Question问题

  • What is the best way to append parameters to a URL?将 append 参数转换为 URL 的最佳方法是什么?
  • How do you put an array into a query string?如何将数组放入查询字符串中?

You can use an array directly in a url, however you would need to serialize the array into a string.您可以直接在 url 中使用数组,但是您需要将数组序列化为字符串。 like this player[]=one&player[]=two像这样player[]=one&player[]=two

here is a little function to automate it.这是一个自动化的小功能。

when using url's you should always use encodeURIComponent to encode any non url friendly characters.使用 url 时,您应该始终使用encodeURIComponent对任何非 url 友好字符进行编码。 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))

edit编辑

The only difference is the function declaration style, everything else is standard ES5唯一的区别是函数声明风格,其他都是标准的 ES5

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

Cleanier:更清洁:

website.com/?players=player1,player2,player3,player4

Then split the query to get result:然后拆分查询以获取结果:

var arrayResult = query.players.split(",")

I'm not certain whether you can even encode arrays, and it might be framework specific if you can我不确定您是否甚至可以对数组进行编码,如果可以,它可能是特定于框架的

query strings are of the format ?a=1&b=2&c=3&... , and adding is straightforward.查询字符串的格式为?a=1&b=2&c=3&... ,添加很简单。 You can definitely pass 6 players as parameters like above你绝对可以像上面一样传递 6 个玩家作为参数

Edit: Per request, query string would look like编辑:每个请求,查询字符串看起来像

website.com/?player1=foobar&player2=foobuz&player3=foobaz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM