Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

Get the query string on the called javascript file

Is it possible to get the query parameters with javascript on the called javascript file like this:

// 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may append id attribute to script tag like this:

<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:

window.onload=function(){
    alert(document.getElementById("query").src.split("query=")[1]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...