Javascript 如何从脚本路径获取查询字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4716612/
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 do I get query string value from script path?
提问by TruMan1
I am adding my Javsacript file in pages with different query strings in the script path like this:
我在脚本路径中具有不同查询字符串的页面中添加我的 Javsacript 文件,如下所示:
Page1:
第1页:
<script type="text/javascript" src="file.js?abc=123"></script>
Page2:
第2页:
<script type="text/javascript" src="file.js?abc=456"></script>
Page3:
第3页:
<script type="text/javascript" src="file.js?abc=789"></script>
In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.
在我的 Javascript 文件中,如何获取“abc”参数的值?我尝试为此使用 window.location ,但这不起作用。
In case it helps, below is a function I use to find the value of a query string param:
如果有帮助,下面是我用来查找查询字符串参数值的函数:
function getQuerystring(key, defaultValue) {
if (defaultValue == null) defaultValue = "";
key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return defaultValue;
else
return qs[1];
}
回答by Ashley
This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (notXHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it's triggered–
这个有可能。请参阅通过 src 属性传递 JavaScript 参数。重点是,由于 HTML(而不是XHTML)中的脚本是在加载时执行的,这将允许脚本找到自己,因为它总是被触发时页面中的最后一个脚本——
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
Then you just apply the query string parsing.
然后您只需应用查询字符串解析。
回答by josh3736
First, the technical answer: if you assign your script tag an ID, you can then grab its src
and then parse out the query string.
首先,技术答案:如果您为脚本标记分配一个 ID,则可以获取它src
,然后解析出查询字符串。
<script id="whatever" type="text/javascript" src="file.js?abc=123"></script>
var path = document.getElementById('whatever').src;
// ...
With that answered, I'd like to voice my concern — this reeks of poor design decisions. Why are you including your script this way (with a querystring)? If you're trying to optimize your site (by having one large script that can be cached for subsequent pages), this approch is actually counter-productivebecause browsers will make a fresh request for the script file on each page due to the differing query string. The correct approach is to have one large shared file and then a small page-specific file on each page.
有了这个答案,我想表达我的担忧——这是糟糕的设计决策的恶臭。为什么要以这种方式(使用查询字符串)包含脚本?如果您正在尝试优化您的网站(通过拥有一个可以为后续页面缓存的大型脚本),这种方法实际上会适得其反,因为浏览器会由于不同的查询而对每个页面上的脚本文件发出新的请求细绳。正确的方法是在每个页面上有一个大的共享文件,然后是一个特定于页面的小文件。
回答by Tanoro
I have a quick and easy solution for extracting the query string from a js file using jQuery to grab the script tag source attribute and simply using two separate functions for parsing the JS file path and query string. Obviously, jQuery is required.
我有一个快速简便的解决方案,用于使用 jQuery 从 js 文件中提取查询字符串以获取脚本标记源属性,并且只需使用两个单独的函数来解析 JS 文件路径和查询字符串。显然,jQuery 是必需的。
$(document).ready(function() {
var p = parseURL($('script[src*="thisfile.js"]').attr('src'));
console.log(p);
});
// Parse a URL into its parts
function parseURL(url)
{
var p = document.createElement('a');
p.href = url;
var obj = {
'protocol' : p.protocol,
'hostname' : p.hostname,
'port' : p.port,
'pathname' : p.pathname,
'search' : p.search,
'query' : p.search.substring(1),
'args' : parseStr(p.search.substring(1)),
'hash' : p.hash,
'host' : p.host
};
return obj;
}
// Parse a query string
function parseStr(string)
{
var args = string.split('&');
var argsParsed = {};
for (i = 0; i < args.length; i++)
{
var arg = decodeURIComponent(args[i]);
if (arg.indexOf('=') == -1)
{
argsParsed[arg.trim()] = true;
}
else
{
var kvp = arg.split('=');
argsParsed[kvp[0].trim()] = kvp[1].trim();
}
}
return argsParsed;
}