gpt4 book ai didi

javascript - 从javascript中的url获取查询字符串

转载 作者:行者123 更新时间:2023-11-30 16:43:05 25 4
gpt4 key购买 nike

我一直在尝试使用 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

最佳答案

问题是 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"

关于javascript - 从javascript中的url获取查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31646179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com