对URL进行编码,以便可以通过GET发送

encode URL so it can be send through GET

本文关键字:可以通过 GET 发送 URL 编码      更新时间:2023-09-26

在javascript中附加URL到查询字符串的最佳方式是什么?我意识到它需要被编码。

我遇到了encodeURIComponent()函数,它看起来像我想要的东西。我只是不确定它是否适合这种任务。

使用例子:

var someURL = encodeURIComponent("http://stackoverflow.com/questions/ask?name=.hil#");
var firstURL = "www.stackoverflow.com/questions?someurl="
firstURL+someURL;

您的选择是encodeURIencodeURIComponentencodeURIComponent是正确的选择,因为您正在编码URL的一部分(这恰好是类似URL的,但在这里无关紧要)。如果您要使用encodeURI,它将无法转换组件中的足够字符。