如何编码 URL 参数?

我试图传递参数到一个 URL,它看起来像这样:

http://www.foobar.com/foo?imageurl=

我想传递一些参数,比如由另一个 API 生成的图像 URL,图像的链接如下:

http://www.image.com/?username=unknown&password=unknown

但是,当我尝试使用 URL 时:

http://www.foobar.com/foo?imageurl=http://www.image.com/?username=unknown&password=unknown

没用的。

我还尝试过在 image URL 上使用 encodeURI()encodeURIComponent(),但这也不起作用。

202571 次浏览

用 PHP

echo urlencode("http://www.image.com/?username=unknown&password=unknown");

结果

http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown

使用 Javascript:

var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);

演示: http://jsfiddle.net/Lpv53/

使用新的 ES6 Object.entries(),它使一个有趣的小嵌套 map/join:

const encodeGetParams = p =>
Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");


const params = {
user: "María Rodríguez",
awesome: true,
awesomeness: 64,
"ZOMG+&=*(": "*^%*GMOZ"
};


console.log("https://example.com/endpoint?" + encodeGetParams(params))

你自己试试 encodeURI()encodeURIComponent()..。

console.log(encodeURIComponent('@#$%^&*'));

Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...

You should not be using encodeURIComponent() or encodeURI(). You should use fixedEncodeURIComponent() and fixedEncodeURI(), according to the MDN Documentation.

Regarding encodeURI()...

If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

Regarding encodeURIComponent()...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

So, what is the difference? fixedEncodeURI() and fixedEncodeURIComponent() convert the same set of values, but fixedEncodeURIComponent() also converts this set: +@?=:*#;,$&. This set is used in GET parameters (&, +, etc.), anchor tags (#), wildcard tags (*), email/username parts (@), etc..

For example -- If you use encodeURI(), user@example.com/?email=me@home will not properly send the second @ to the server, except for your browser handling the compatibility (as Chrome naturally does often).

URLSearchParams:

const params = new URLSearchParams()
params.append('imageurl', 'http://www.image.com/?username=unknown&password=unknown')
return `http://www.foobar.com/foo?${params.toString()}`