如何使用JavaScript安全地编码URL,以便将其放入GET字符串中?

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

我假设您需要在第二行编码myUrl变量?


当前回答

使用fixedEncodeURIComponent函数严格遵守RFC 3986:

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

其他回答

encodeURIComponent()是最好的方法。

var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

但是您应该记住,与PHP版本urlencode()有一些小的不同,正如@CMS所提到的,它不会对每个字符进行编码。伙计们在http://phpjs.org/functions/urlencode/使JavaScript等效于phpencodes():

function urlencode(str) {
  str = (str + '').toString();

  // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  return encodeURIComponent(str)
    .replace('!', '%21')
    .replace('\'', '%27')
    .replace('(', '%28')
    .replace(')', '%29')
    .replace('*', '%2A')
    .replace('%20', '+');
}

现代解决方案(2021)

自从编写了其他答案后,就引入了URLSearchParams API。它可以这样使用:

const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1&param2=value2'

它还编码非URL字符。

对于您的具体示例,您可以这样使用:

常量myUrl=“http://example.com/index.html?param=1&anotherParam=2";const myOtherUrl=新URL(“http://example.com/index.html");myOtherUrl.search=新URLSearchParams({url:myUrl});console.log(myOtherUrl.toString());

这个解决方案也在这里和这里提到。

如前所述,要对URL进行编码,您有两个函数:

encodeURI()

and

encodeURIComponent()

两者都存在的原因是,第一种方法保留了URL,但有可能留下太多未被屏蔽的内容,而第二种方法对所有需要的内容进行编码。

使用第一个,您可以将新转义的URL复制到地址栏中(例如),这样就可以了。然而,未转义的‘&’会干扰字段分隔符,‘=’会干扰域名和值,‘+’看起来像空格。但对于简单的数据,当您希望保留要转义的内容的URL性质时,这是有效的。

第二个是您需要做的一切,以确保字符串中没有任何内容干扰URL。它保留了各种不重要的字符,使URL尽可能保持可读性而不受干扰。以这种方式编码的URL将不再作为URL工作,而不会取消其标题。

因此,如果您可以花点时间,那么在添加名称/值对之前,您总是希望使用encodeURIComponent()对名称和值进行编码,然后再将其添加到查询字符串中。

我很难找到使用encodeURI()的理由——我将把这留给更聪明的人。

没有什么对我有用。我看到的只是登录页面的HTML,返回到客户端,代码为200。(最初是302,但相同的Ajax请求在另一个Ajax请求中加载登录页面,这应该是一个重定向,而不是加载登录页面的纯文本)。

在登录控制器中,我添加了以下行:

Response.Headers["land"] = "login";

在全局Ajax处理程序中,我这样做了:

$(function () {
    var $document = $(document);
    $document.ajaxSuccess(function (e, response, request) {
        var land = response.getResponseHeader('land');
        var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
        if(land) {
            if (land.toString() === 'login') {
                window.location = redrUrl;
            }
        }
    });
});

现在我没有任何问题,它就像一个魅力。

查看内置函数encodeURIComponent(str)和encodeURI(str)。在您的情况下,这应该有效:

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);