How to access a query-string in a javascript file

走远了吗. 提交于 2020-01-22 02:20:15

问题


Possible Duplicate:
How can I get query string values?

Lets say, we have a <script> tag like this in the HTML markup

<script src="/path/file.js?test=1&data=2"></script>

..is there any way to access the query-string within file.js ? window.location does not change of course, so you can't use that for that.

If this is not possible, how can you pass data into a script file ?


回答1:


Musa has the right approach here (from the comments). You can access the script tag like any other (you can use an ID to make it easy):

<script id='my_script_1' src="/path/file.js?test=1&data=2"></script>

Then just parse out the src and grab only the query string:

var js_lib = document.getElementById('my_script_1');
var js_url = js_lib.src;
var js_url_pieces = js_url.split('?');
alert(js_url_pieces[1]);

Note: I'm using split for simplicity's sake. You might want to use regex.

If you want reload the js file, just reset the source:

js_lib.src = js_url_pieces[0]+'?new query string';

I think that should work in most browsers.

Alternately, as others have mentioned, you might want to write more flexible functions or use global variables to achieve what you're trying to do through _GET vars.




回答2:


The only reliable way I can think of is via document.currentScript but that is currently supported only by Firefox.

This question may have some useful information.

To pass data into a script file, I may use global variables. I don't really like them in general but this may be an appropriate use for them.




回答3:


It sounds like you want to pass some data from the parent document, into your included javascript file. You could do it with a global variable, like so

your-file.html:

<script>
var myVar = "Hi";
</script>
<script src="script.js"></script>

script.js:

alert(myVar);



回答4:


When the script runs, that script is the last element on the page (due to JavaScript being blocking). You can take advantage of this:

var scripts = document.getElementsByTagName('script'),
    me = scripts[scripts.length-1],
    myurl = me.getAttribute("src"),
    myquery = myurl.split("?")[1].split("#")[0].split("&"),
    qcount = myquery.length, query = {}, i, tmp;
for( i=0; i<qcount; i++) {
    tmp = myquery[i].split("=");
    query[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
}

Note that this will only work if it's in the outermost scope of the code, ie. not in a function. It also won't work for async or deferred scripts.



来源:https://stackoverflow.com/questions/12504359/how-to-access-a-query-string-in-a-javascript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!