从 html 页面访问查询字符串/参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10043412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing query string/parameter from html page
提问by Jeff Fol
I have a basic html page which is having a query parameter being passed to the page. I thought I would be able to get the value with Request.QueryString but the more reading I'm doing seems that this is only for asp applications. My html is as follows below
我有一个基本的 html 页面,它有一个查询参数被传递到页面。我以为我可以使用 Request.QueryString 获得该值,但是我正在做的更多阅读似乎仅适用于 asp 应用程序。我的html如下
<body>
<object type="application/pdf" width="100%" height="100%">
<!--This didn't work-->
<param name="src" value="<%=Request.QueryString["path"]%>" />
<!--Neither did this-->
<!--<param name="src" value="<%=Request.Params["path"]%>" />-->
<!--When it is hardcoded then my page is displaying the pdf as expected.-->
<!--<param name="src" value="scan.pdf" />-->
</object>
</body>
I am calling the page with displayPdf.htm?path=scan.pdf
我用 displayPdf.htm?path=scan.pdf 调用页面
I've been searching for a way to access query parameters in html without having to write a javascript solution but haven't had any luck. I'm sure adding a js function wouldn't be too big a deal just thought I would avoid it if there was a single line approach.
我一直在寻找一种无需编写 javascript 解决方案即可访问 html 中的查询参数的方法,但没有任何运气。我确信添加一个 js 函数不会太重要,只是想如果有单行方法我会避免它。
Thanks for the help.
谢谢您的帮助。
回答by Rob W
This cannot be done in pure HTML.
这不能在纯 HTML 中完成。
This can be done in two ways, using JavaScript:
这可以通过两种方式完成,使用 JavaScript:
<body><script>
var param = /[&?]path=([^&]+)/.exec(location.search);
param = param ? param[1].replace(/"/g, '"') : '';
document.write('<object type="application/pdf" width="100%" height="100%">\n' +
'<param name="src" value="' + param + '" />\n</object>');
</script></body>
An alternative method is populating the parameter using DOM (demo: http://jsfiddle.net/N2GUf/2/):
另一种方法是使用 DOM 填充参数(演示:http: //jsfiddle.net/N2GUf/2/):
<body><object type="application/pdf" width="100%" height="100%">
? ??<param name="src" value="" id="param-path" />
</object>
<script>
var param = /[&?]path=([^&]+)/.exec(location.search);
if (param)
? ??document.getElementById('param-path').value = param[1];
</script>?</body>
In either case, the query string is read from the location.search
property, and parsed using a simple regular expression.
在任何一种情况下,查询字符串都是从location.search
属性中读取的,并使用简单的正则表达式进行解析。