【问题标题】:Getting undefined error when using Request.QueryString() to get variuable value使用 Request.QueryString() 获取变量值时出现未定义错误
【发布时间】:2010-08-20 14:06:46
【问题描述】:

我正在使用以下代码打开一个弹出窗口并将 ID 作为查询字符串传递。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript" type="text/javascript">
function openwindow(divID) {
           window.open("pp.html?id="+divID+"","","status=yes, location=yes, width=700, height=400");
   }
</script>
</head>
<body>
<a href="#" onclick="openwindow('one')" id="one">One</a>
<br />
<a href="#" onclick="openwindow('two')" id="two">Two</a>
<br />
<a href="#" onclick="openwindow('three')" id="three">Three</a>
</body>
</html>

场景是,我需要在弹出窗口中显示 id 类似于查询字符串值的 DIV。弹窗代码是

<html>
<head>
<script language="javascript" type="text/javascript">
function getid() {
    if (Request.QueryString("id")!=null)
        var id = Request.QueryString("id");
        document.getElementById(id).style.display = "block";
}
</script>
</head>
<body onload="getid();">
<div style=" overflow:hidden">
<div style="margin-left:-5px;"><input type="file" style="" /></div>
</div>
<div style="width:200px; height:200px; border:1px solid #999999; background-  color:#CCCCCC; display:none" id="one">Hello! ONE</div>
<div style="width:200px; height:200px; border:1px solid #999999; background-color:#CCCCCC; display:none" id="two">Hello! TWO</div>
<div style="width:200px; height:200px; border:1px solid #999999; background-color:#CCCCCC; display:none" id="three">Hello! THREE</div>
</body>
</html>

现在,弹出窗口给出错误“请求未定义”。

【问题讨论】:

    标签: javascript request.querystring


    【解决方案1】:

    您正在将 ASP.NET 服务器端语言与 javascript 混合,这当然是不可能的。试试这样:

    function getid() {
        <% if (Request.QueryString("id") != null) { %>
            var id = '<%= Request.QueryString("id") %>';
            document.getElementById(id).style.display = 'block';
        <% } %>
    }
    

    如果您不使用服务器端语言,您可以使用以下函数读取 javascript (taken from here) 中的查询字符串参数:

    function gup(name)
    {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null ) {
            return "";
        } else {
            return results[1];
        }
    }
    

    并像这样使用:

    function getid() {
        var id = gup('id');
        if (id != '') {
            document.getElementById(id).style.display = 'block';
        }
    }
    

    【讨论】:

    • 哇!你的简单 HTML 的 javascript 代码就像你救了我达林的魅力一样,非常感谢:)
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2022-06-14
    • 2013-08-01
    相关资源
    最近更新 更多