我正在尝试 alert
jquery 中的查询字符串参数,因为我需要在页面加载时使用 ID
以便我可以在加载控件时创建一些 html 元素。我似乎无法访问该参数,因为 URL 就地重写并且 URL 看起来与原始 URL 不同。
原始网址
www.somesite.com/camping?ProductId=2457&ism=0&cl=PURPLE
在浏览器中看到的 URL
www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE
现在,我如何在 Jquery 中访问 ProductId 查询字符串值。
查询
$(document).ready(function () {
var param = getParameterByName("ProductId");
alert(param) // shows PURPLE as cl in URL is set to cl=PURPLE
});
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, " "));
}
编辑:
这是我尝试访问服务器端的 Querysting 对象时的屏幕截图。
最佳答案
您当前的代码正在尝试访问查询字符串中的值,该值已不存在,因为它已在服务器上被重写。
您可以使用正则表达式来剖析重写的 URL,不需要 jQuery。假设您的 productId
始终以 -p
开头并紧跟 .aspx
,那么这将起作用:
var url = 'www.somesite.com/camping/travel-mug-16oz-double-wat-with-adapter-p2457.aspx?ism=0&cl=PURPLE'
var matches = url.match(/-p(\d+)\.aspx/);
var productId = matches && matches[1];
console.log(productId); // = 2457
如果没有匹配到正则表达式,productId
将为 null
。
关于javascript - 如何使用 URL 重写在 javascript 中访问 REAL querystring 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19517625/