【发布时间】: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 时,它会失败,为 prodID 和 prodName 提供空字符串
【问题讨论】:
-
为我工作。检查this
-
查询字符串必须在哈希之前。 URL 应为
http://192.168.0.216:1009/main.html?id=123&name=test#!/video.html -
@Barmar 可能 OP 使用了一些 SPA 框架,其中查询字符串是这样模拟的。
-
如果
#打算成为路径名的一部分,他可能需要对它进行 URL 编码。