如何访问JavaScript文件中的查询字符串 [英] How to access a query-string in a javascript file

查看:73
本文介绍了如何访问JavaScript文件中的查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何获取查询字符串值?

Possible Duplicate:
How can I get query string values?

可以说,我们在HTML标记中有一个<script>标记

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

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

..是否可以访问file.js中的查询字符串? window.location当然不会改变,所以您不能为此使用它.

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

推荐答案

Musa在此处采用正确的方法(根据评论).您可以像访问其他脚本标签一样访问脚本标签(可以使用ID来简化此操作):

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>

然后只需解析src并仅获取查询字符串:

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]);

注意:为了简单起见,我使用split.您可能要使用正则表达式.

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

如果要重新加载js文件,只需重置源:

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.

或者,就像其他人提到的那样,您可能想编写更灵活的函数或使用全局变量来实现通过_GET vars尝试执行的操作.

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.

这篇关于如何访问JavaScript文件中的查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆