【问题标题】:JS decodeURIComponent returns empty string in Firefix (most recent)JS decodeURIComponent 在 Firefox 中返回空字符串(最新)
【发布时间】:2016-08-20 01:51:33
【问题描述】:

从 StackOverflow 获得以下代码。它应该解析 URL 中的变量,但是当我在 for 循环中调试 sURLVariables 的值时,它的值始终为空。任何想法为什么?

var getUrlParameter = function getUrlParameter(sParam) {
  var sPageURL = decodeURIComponent(window.location.search.substring(1)), 
      sURLVariables = sPageURL.split('&'), sParameterName, i;

  for (i = 0; i < sURLVariables.length; i++) {
    sParameterName = sURLVariables[i].split('=');

    if (sParameterName[0] === sParam) {
      return sParameterName[1] === undefined ? true : sParameterName[1];
    }
  }
};

【问题讨论】:

  • PS 由于某种未知原因(对我而言),我也无法将所有代码放入代码块中。
  • window.location.search.substring(1) 的值是多少?
  • 另外,您提到了 Firefox……这是否意味着您在其他浏览器上看到了不同的行为?
  • 我所有的调试扩展都是针对 Firefox 的,所以不确定 window.location.search.substring(1) 返回的确切值,但是通过 alert() 输出它;也返回一个空字符串。因此,Firefox 和 Chrome(均为最新版本)中的行为是相同的。并且刚刚在 Firefox 中检查了它的确切值——它是一个空字符串。
  • 我已将示例上传到atomz.host-ed.me/#?l=en。我正在测试网站的不同口语。如果您单击其中一个标志,它应该会更改浏览器标题,但它不会。

标签: javascript decodeuricomponent


【解决方案1】:

您使用的代码会查找 URL 的“搜索”部分(查询字符串),但您使用的页面没有任何查询字符串。您页面上的 URL 类似于 http://www.atomz.host-ed.me/#?l=en。哈希 (#) 之后的所有内容都是 URL fragment 的一部分。

使用window.location.hash.substring(2),而不是window.location.search.substring(1)

(或者去掉URL片段开头的问号,使用window.location.hash.substring(1)。)

【讨论】:

  • 谢谢。这解决了问题。还必须添加一个事件处理程序以在哈希更改时重新加载页面,以使其适用于我的情况。 window.onhashchange = function() { location.reload(); }
  • @AaronLowe 与其刷新页面并在页面加载时执行此工作,不如在哈希更改时执行此工作。
  • 网址中有哈希的原因是为了链接到当前页面,并使用设置语言的变量。因为无论如何都必须重新加载整个页面,因为所有内容都发生了变化,所以没有那么麻烦。我可以通过加载大量 id 并动态更改元素内容来实现相同的目标,但这似乎有点过头了。
  • 毫无疑问有更好的方法,但我不是网页设计师 - 只是一个业余涉足者。我想先让整个概念发挥作用,然后再考虑提高效率。
【解决方案2】:

尝试使用window.location.hrefdocument.URL获取当前页面的完整URL。更多关于他们:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Document/location
  2. https://developer.mozilla.org/en-US/docs/Web/API/Document/URL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    相关资源
    最近更新 更多