繁体   English   中英

javascript Request.QueryString

[英]javascript Request.QueryString

如何使用来自 URL 的 javascript 请求查询字符串

例如: http://localhost:1247/portal/alias__MySite/lang__en/tabid__3381/default.aspx

我想听话.. .

 var tabid = '<%= Request.QueryString["tabid"] %> ';

以上代码仅适用于 aspx 页面,但我不需要它,有什么想法吗? 谢谢

现在有一个新的 api URLSearchParams 将其与window.location.search结合使用

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('tabid'));

如果您的浏览器不支持URLSearchParams ,您可以创建自定义后备 function:

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

试试这个,它对我来说非常有用。

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, " "));
}

var tabId=getParameterByName("tabid");

不知道为什么,但我总是发现 javascript 用于获取查询字符串数据有点 hacky。 如果您在初始页面加载时不需要此值,那么也许您可以在代码中使用 Request.QueryString 并将值设置为隐藏字段,您的 javascript 将从中读取?

这是我使用的:

<script type="text/javascript">   

function QueryString(key) {  
//Get the full querystring  
fullQs = window.location.search.substring(1);  
//Break it down into an array of name-value pairs  
qsParamsArray = fullQs.split("&");  
//Loop through each name-value pair and   
//return value in there is a match for the given key  
for (i=0;i<qsParamsArray.length;i++) {  
strKey = qsParamsArray[i].split("=");  
    if (strKey[0] == key) {  
        return strKey[1];  
    }  
}  
}  

//Test the output (Add ?fname=Cheese&lname=Pizza to your URL)  
//You can change the variable to whatever it is you need to do for example, you could  
//change firstname to id and lastname to userid and just change the reference in the
//document.write/alert box
var firstname = QueryString("fname"); 
var lastname = QueryString("lname");   
document.write("You are now logged in as " + firstname + " " + lastname + "!");  

</script>

你可以用 alert 替换 document.write ,它会给你一个警告框!

我在我的网站上使用了这个。 它还没有完成,但它会在 zducttapestuff.com

output 将如下所示: 您现在以 Cheese Pizza 的身份登录!

这对于密码来说是非常不安全的,因为密码将显示在 url 中。

我敢打赌有一个服务器端重写(DotNetNuke?),所以 aspx.cs“看到”包含正确 QueryString 的重定向目标。

对于客户端,您必须使用另一种机制,因为浏览器只能“看到”公共 URL。 在这种情况下,选择“tabid_”后面和下一个斜杠之前的数字的正则表达式应该可以工作。 这将是 aspx 页面“看到”的相同数字(页面 id?)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM