如何从脚本路径获取查询字符串值? [英] How do I get query string value from script path?
问题描述
Page1:
$ b $在页面中添加我的Javsacript文件,其脚本路径中包含不同的查询字符串,如下所示: b
< script type =text / javascriptsrc =file.js?abc = 123>< / script>
第2页:
< script type =text / javascriptsrc =file.js?abc = 456>< / script>
第3页:
< script type =text / javascriptsrc =file.js?abc = 789>< / script>
在我的Javascript文件中,如何获得abc参数的值?我尝试使用window.location这一点,但这并不奏效。
如果有帮助,下面是一个函数,我用它来查找查询字符串param的值:
函数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];
这是可能的。请参阅通过src属性传递JavaScript参数。值得一提的是,由于HTML中的脚本( not XHTML)是以加载的方式执行的,因此脚本可以找到它自己,因为它始终是触发时页面中的最后一个脚本 -
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts [index];
// myScript现在包含我们的脚本对象
var queryString = myScript.src.replace(/ ^ [^ \?] + \ ?? /,'');
然后您只需应用查询字符串解析。
I am adding my Javsacript file in pages with different query strings in the script path like this:
Page1:
<script type="text/javascript" src="file.js?abc=123"></script>
Page2:
<script type="text/javascript" src="file.js?abc=456"></script>
Page3:
<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.
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];
}
This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (not XHTML) 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–
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.
这篇关于如何从脚本路径获取查询字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!