在Javascript中,是否可以将变量传递给< script> " SRC"参数? [英] In Javascript, is it possible to pass a variable into <script> "src" parameter?

查看:61
本文介绍了在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

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;

这篇关于在Javascript中,是否可以将变量传递给&lt; script&gt; &QUOT; SRC&QUOT;参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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