【问题标题】:Get query string from url in javascript从javascript中的url获取查询字符串
【发布时间】:2015-07-27 06:23:45
【问题描述】:

我一直在尝试使用 javascript 从 url 获取 query string

我正在使用以下代码

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function() {
    prodId = getParameterByName('id');
    prodName = getParameterByName('name');
});

它适用于像http://my_ip/main.html?id=123&name=test这样的URL

但是当 URL 类似于 http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test 时,它会失败,为 prodIDprodName 提供空字符串

【问题讨论】:

  • 为我工作。检查this
  • 查询字符串必须在哈希之前。 URL 应为http://192.168.0.216:1009/main.html?id=123&name=test#!/video.html
  • @Barmar 可能 OP 使用了一些 SPA 框架,其中查询字符串是这样模拟的。
  • 如果 # 打算成为路径名的一部分,他可能需要对它进行 URL 编码。

标签: javascript query-string


【解决方案1】:

问题是http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test 没有location.search 部分。它有 location.hash - # 字符之后的所有内容。

您可以做的简单的事情是修改函数以便也能够使用 location.hash。比如这样:

function getParameterByName(name, useHash) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location[useHash ? 'hash' : 'search']);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

然后像这样使用它:

var prodId = getParameterByName('id', true); // true - use location.hash for "query parameters"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 2013-04-28
    • 2018-08-04
    • 2011-08-30
    • 2012-04-09
    • 2012-04-24
    • 2012-12-24
    • 1970-01-01
    相关资源
    最近更新 更多