encodeURI(JSON.stringify())在URL中显示%255B

Ian*_*nny 1 javascript urlencode encodeuricomponent query-parameters

我试图通过Angular中的queryParam,它由这样的对象数组组成fooArray = [{foo: 'bar', foo: false}, {foo: 'bar', foo: false}]。在URL queryParam中,我收到以下消息:使用时,%255BencodeURI(JSON.stringify(this.fooArray))

我试过使用encodeURI(JSON.stringify())将数组编码为queryParam和JSON.parse(decodeURIComponent())以检索参数

fooArray = [{foo: 'bar', foo: false}, {foo: 'bar', foo: false}]

fooParam: encodeURI(JSON.stringify(this.fooArray))

JSON.parse(decodeURIComponent(params["fooParam"]))

T.J*_*der 5

您正在对该网址进行双重编码。这个:

encodeURI(JSON.stringify([{foo: 'bar', foo: false}, {foo: 'bar', foo: false}]))
Run Code Online (Sandbox Code Playgroud)

结果是

"%5B%7B%22foo%22:false%7D,%7B%22foo%22:false%7D%5D"
Run Code Online (Sandbox Code Playgroud)

如果encodeURI再次调用它,您会得到

"%255B%257B%2522foo%2522:false%257D,%257B%2522foo%2522:false%257D%255D"
Run Code Online (Sandbox Code Playgroud)

...因为%被编码为%25

两个注意事项:

  1. 您应该只对其编码一次。也许您要将字符串传递给已经为您进行URI编码的字符串?如果是这样,请不要使用encodeURI

  2. 通常,您不需要encodeURIComponentencodeURI(因为通常只编码hte URI的一个组成部分,而不是整个内容)。