Javascript 如何编码 URL 参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8135132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:49:55  来源:igfitidea点击:

How to encode URL parameters?

javascripturlencodeuricomponent

提问by Apoorv Saxena

I am trying to pass parameters to a URL which looks like this:

我正在尝试将参数传递给如下所示的 URL:

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

and I want to pass the parameters suchas and image URL which is generated itself by another API, and the link for the image turns out as:

我想传递由另一个 API 自身生成的参数和图像 URL,图像的链接结果为:

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

However, when I try to use the URL:

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

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

it doesn't work..

它不起作用..

I have also tried using encodeURI and encodeURIComponents on the imageURL, and that too doesn't work.

我也试过在 imageURL 上使用 encodeURI 和 encodeURIComponents,但这也不起作用。

回答by Niels

With PHP

使用 PHP

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

Result

结果

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

With Javascript:

使用 JavaScript:

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

DEMO: http://jsfiddle.net/Lpv53/

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

回答by Kyle VanderBeek

Using new ES6 Object.entries(), it makes for a fun little nested map/join:

使用新的 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))