javascript 获取被调用的javascript文件上的查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15223884/
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
Get the query string on the called javascript file
提问by Adam
Is it possible to get the query parameters with javascript on the called javascript file like this:
是否可以在被调用的 javascript 文件上使用 javascript 获取查询参数,如下所示:
// in html
<script src="/file.js?query=string"></script>
// in file.js
console.log(this.location.query)
Is this possible somehow, or I have to use the server?
这可能以某种方式实现,还是我必须使用服务器?
采纳答案by Jiri Tobisek
No, it is not possible, because the script file has no representation within the global javascript scope. You can only find its element inside the DOM as shown by haitaka, but this is a highly non-standard and certainly not recommended way to pass parameters to script.
不,这是不可能的,因为脚本文件在全局 javascript 范围内没有表示。您只能在 DOM 中找到它的元素,如 haitaka 所示,但这是一种高度非标准的方法,当然不推荐将参数传递给脚本。
回答by haitaka
You may append id attribute to script tag like this:
您可以将 id 属性附加到脚本标签,如下所示:
<script src="/file.js?query=string" id="query"></script>
and then call it:
然后调用它:
console.log(document.getElementById("query").src.split("query=")[1]);
A small working sample code is below:
一个小的工作示例代码如下:
<html>
<head>
<script src="aaa.js?query=abcd" id="query"></script>
</head>
<body></body>
</html>
Here is the code inside of aaa.js:
这是 aaa.js 中的代码:
window.onload=function(){
alert(document.getElementById("query").src.split("query=")[1]);
}
回答by Igari Takeharu
I could get src with below code. So I think that you can parse queryString.
我可以使用以下代码获取 src。所以我认为你可以解析queryString。
document.currentScript.src
回答by RayLuo
I know this is old, but I thought you wouldn't mind (yet another) two more cents...
我知道这是旧的,但我想你不会介意(又一个)两美分......
If you are NOT adding an id to the script element, James Smith has a snippet that does not require an id attribute. And that id-less characteristic is huge, because your script file does NOT need to couple with an ID in the caller's side.
如果您不向脚本元素添加 id,James Smith 有一个不需要 id 属性的片段。并且这种无 id 特性是巨大的,因为您的脚本文件不需要与调用方的 ID 耦合。
// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
// Find all script tags
var scripts = document.getElementsByTagName("script");
// Look through them trying to find ourselves
for(var i=0; i<scripts.length; i++) {
if(scripts[i].src.indexOf("/" + script_name) > -1) {
// Get an array of key=value strings of params
var pa = scripts[i].src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
}
// No scripts match
return {};
}
回答by Sithu
In file.js
, the current script is the last script of all files being included. So, you can get it by the following way:
在 中file.js
,当前脚本是包含的所有文件的最后一个脚本。因此,您可以通过以下方式获取它:
var scripts = document.getElementsByTagName('script');
var currentScript = scripts[scripts.length-1];
if (currentScript.src.indexOf('app_key') !== -1) {
console.log(currentScript.src.split('query=')[1])
}
回答by Fabien Snauwaert
You can use document.currentScript.src
(only at the appropriate time) and URLSearchParams
to extract the query string from the called JavasScript file.
您可以使用document.currentScript.src
(仅在适当的时间)和URLSearchParams
从被调用的 JavaScript 文件中提取查询字符串。
Example:
例子:
In your HTML:
在您的 HTML 中:
<script src="querystring.js?foo=bar&foo=bar2"></script>
In your JavaScript file:
在您的 JavaScript 文件中:
/**
* When this is being run, the document's last element will be this very script.
* Explanations on http://feather.elektrum.org/book/src.html
*/
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// document.currentScript.src will be this file's URL, including its query string.
// e.g. file:///mytests/querystring.js?foo=script
/**
* Now just turn the query string (if any) into a URLSearchParams
to let us easily check values.
*/
var querystring = document.currentScript.src.substring( document.currentScript.src.indexOf("?") );
var urlParams = new URLSearchParams( querystring );
console.log( urlParams.getAll('foo') ); // Array [ "bar", "bar2" ]
Keep in mind:
记住:
- This might not work when the script is included via async.
- get or getAll?
urlParams.get
will only return the first value (as a string)urlParams.getAll
will return an array (of size 1 if just one value is provided.)
- 当通过异步包含脚本时,这可能不起作用。
- 获取或获取全部?
urlParams.get
只会返回第一个值(作为字符串)urlParams.getAll
将返回一个数组(如果只提供一个值,则大小为 1。)
I hope this helps.
我希望这有帮助。
回答by jacobfogg
I know this is old, but I thought I'd throw in my two cents...
我知道这很旧,但我想我会投入我的两分钱......
If you are already adding an id to the script element, why not add a custom attribute as well:
如果您已经在脚本元素中添加了一个 id,为什么不添加一个自定义属性:
<script src="/file.js" id="query" value="string"></script>
Then you can grab the value using getAttribute:
然后你可以使用 getAttribute 获取值:
document.getElementById('query').getAttribute('value');
回答by Dineshkani
Try like this to get the value of query using javascript
尝试这样使用javascript获取查询的值
alert(window.location.href.split["?"][1].split["="][1]);