如何通过 url 将参数传递给 javascript 并将其显示在页面上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2405355/
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
How to pass a parameter to a javascript through a url and display it on a page?
提问by Frank
For instance, I have a url like this : www.mysite.com/my_app.html
例如,我有一个这样的网址:www.mysite.com/my_app.html
How do I pass a value " Use_Id = abc " to it and use javascript to display on that page ?
如何将值“Use_Id = abc”传递给它并使用 javascript 在该页面上显示?
回答by Andy E
Shouldn't be too difficult to write your own without the need for an external library.
在不需要外部库的情况下编写自己的库应该不会太难。
// www.mysite.com/my_app.html?Use_Id=abc
var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
if (query[i] === "") // check for trailing & with no param
continue;
var param = query[i].split("=");
GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}
Usage: GET.Use_idor GET["Use_id"]. You can also check if a parameter is present even if it has a null value using "Use_id" in GET(will return true or false).
用法:GET.Use_id或GET["Use_id"]。您还可以使用"Use_id" in GET(将返回真或假)检查参数是否存在,即使它具有空值。
回答by Mic
Call the page www.mysite.com/my_app.html?Use_Id=abc
调用页面 www.mysite.com/my_app.html?Use_Id=abc
Then in that page use a javascript function like:
然后在该页面中使用一个 javascript 函数,如:
var urlParam = function(name, w){
w = w || window;
var rx = new RegExp('[\&|\?]'+name+'=([^\&\#]+)'),
val = w.location.search.match(rx);
return !val ? '':val[1];
}
To use it:
要使用它:
var useId = urlParam('Use_Id');
The second parameter wis optional, but useful if you want to read parameters on iframes or parent windows.
第二个参数w是可选的,但如果您想在 iframe 或父窗口上读取参数,则很有用。
回答by Byron Whitlock
回答by Dustin Laine
www.mysite.com/my_app.html?Use_Id=abc
var querystring = window.location.querystring;
var myValue = querystring["Use_Id"];
UPDATE: Link to library (thanks @Andy E), http://prettycode.org/2009/04/21/javascript-query-string/
更新:链接到图书馆(感谢@Andy E),http://prettycode.org/2009/04/21/javascript-query-string/
回答by Ceilingfish
There's a similar question on this here What is the easiest way to read/manipulate query string params using javascript?
这里有一个类似的问题What is the most simple way to read/manipulate query string params using javascript?
Which seems to recommend using jQuery's Querystring plugin: http://plugins.jquery.com/project/query-object
这似乎建议使用 jQuery 的 Querystring 插件:http: //plugins.jquery.com/project/query-object
回答by Mat Barnett
Your server side script could read the value and set it in a hidden form field which your JS could then read.
您的服务器端脚本可以读取该值并将其设置在您的 JS 可以读取的隐藏表单字段中。

