在Javascript中,是否可以将变量传递给< script> " SRC"参数?
Javascript中是否可以通过 src
参数传递变量? ie。
Is it possible in Javascript to pass a variable through the src
parameter? ie.
<script type="text/javascript" src="http://domain.com/twitter.js?handle=aplusk" />`
我想 twitter。 js
在执行我需要它做的事情之前查看是否传递了句柄并将其响应返回到调用 twitter.js $ c的原始页面$ c>。
I'd like twitter.js
to look and see if a "handle" was passed before doing what I need it to do and returning its response back to the originating page calling twitter.js
.
我最初在 twitter.js
中创建了一个函数,它执行了以下操作:
I had originally created a function in twitter.js
that did the following:
function getHandle() {
var vars = [], hash, username;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash[0] == 'handle')
username = hash[1];
}
return username;
}
问题,这是有道理的,window.location.href是我打算从< script src =/>
The problem, and it makes sense, is that window.location.href is not going to work on a file that I'm calling from <script src="" />
谢谢!
我在这里可以看到两种解决方案。
I can see two solutions here.
第一:您可以在托管twitter.js的服务器上处理这些GET参数,以便它可以动态更改js文件。例如,您的文件是:
First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:
var handle = {{ handle }};
你的服务器以某种方式处理文件,取代发送的请求取代twitter.js模板文件。
And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.
第二个选项是在加载twitter.js的页面上设置全局变量,如下所示:
The second option would be to set the global variables on the page where twitter.js is loaded, like this:
<script type="text/javascript">
window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />
在twitter.js中:
And in twitter.js:
var handle = window.twitter_js_handle || null;