在 Javascript 中,是否可以将变量传递到

Javascript 中是否可以通过 src 参数传递变量? IE。

<script type="text/javascript" src="http://domain.com/twitter.js?handle=aplusk" />`

我希望 twitter.js 在执行我需要的操作并将其响应返回到调用 twitter.js 的原始页面之前查看是否传递了“句柄” /代码>。

我最初在 twitter.js 中创建了一个函数,该函数执行以下操作:

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 不适用于我正在调用的文件来自

谢谢!

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" />`

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.

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;
}

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="" />

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

美羊羊 2024-10-15 22:41:36

我可以在这里看到两个解决方案。

首先:您可以在托管 twitter.js 的服务器上处理这些 GET 参数,以便它动态更改 js 文件。例如,您的文件是:

var handle = {{ handle }};

并且您的服务器以某种方式处理该文件,根据发送的请求替换该 twitter.js 模板文件。

第二个选项是在加载 twitter.js 的页面上设置全局变量,如下所示:

<script type="text/javascript">
    window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />

在 twitter.js 中:

var handle = window.twitter_js_handle || null;

I can see two solutions here.

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 }};

And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.

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

And in twitter.js:

var handle = window.twitter_js_handle || null;
扎心 2024-10-15 22:41:36

我使用以下模式将查询变量从 转换为包含键:值对的对象。代码放置在 script.js 的顶部:

    var getVars = {};
    
    (function(){
        var scripts, currentScript, queryString;

        scripts = document.getElementsByTagName('script');
        currentScript = scripts[ scripts.length - 1 ];
        queryString = currentScript.getAttribute('src').split("?").pop().split('&');
        for(var i=0;i<queryString.length;i++){
            var keyVal = queryString[i].split('=');
            getVars[ keyVal[0] ] = keyVal[1];
        }
    
    }());
    // console.info( getVars );
    // Object { foo="bar", baz="zing"}

这可能不适用于延迟/异步添加的脚本元素,因为它依赖于立即代码执行。

I use the following pattern to convert query variables from <script src="script.js?foo=bar&baz=zing"></script> to an object containing key:value pairs. Code is placed at the top of script.js:

    var getVars = {};
    
    (function(){
        var scripts, currentScript, queryString;

        scripts = document.getElementsByTagName('script');
        currentScript = scripts[ scripts.length - 1 ];
        queryString = currentScript.getAttribute('src').split("?").pop().split('&');
        for(var i=0;i<queryString.length;i++){
            var keyVal = queryString[i].split('=');
            getVars[ keyVal[0] ] = keyVal[1];
        }
    
    }());
    // console.info( getVars );
    // Object { foo="bar", baz="zing"}

This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.

心头的小情儿 2024-10-15 22:41:36

当然。但访问该参数的唯一方法是通过服务器端。因此,让 twitter.js 成为一个 PHP 页面(使用 mod_rewrite 或其他)来获取 $_GET['handle'] ,然后将其自身作为 Content-Type: text/javascript然后转储 js 的内容。

Sure. But the only way you can access that parameter though is through server-side. So, make twitter.js a PHP page (using mod_rewrite or whatever) that grabs $_GET['handle'] and then serves itself as Content-Type: text/javascript and just dump the contents of the js.

拥有 2024-10-15 22:41:36

我建议使用更安全的方法 - 必须添加一个 ID:

<script id="myTargetScript" src="http://example.com/file.js?param=value" />

然后在您的 .js 文件中

    function GetParams(target_id)
    {
        var getVars = {};
        if( document.getElementById(target_id) )
        {
            var queryString = document.getElementById(target_id).getAttribute('src').split("?").pop().split("&");
            for(var i=0;i<queryString.length;i++){
                var keyVal = queryString[i].split('=');
                getVars[ keyVal[0] ] = keyVal[1];
            }
        }
        return getVars;
    }
        
        
    // console.log(   GetParams('myTargetScript')   );

I suggest to use more safe approach - must add an ID:

<script id="myTargetScript" src="http://example.com/file.js?param=value" />

then in your .js file

    function GetParams(target_id)
    {
        var getVars = {};
        if( document.getElementById(target_id) )
        {
            var queryString = document.getElementById(target_id).getAttribute('src').split("?").pop().split("&");
            for(var i=0;i<queryString.length;i++){
                var keyVal = queryString[i].split('=');
                getVars[ keyVal[0] ] = keyVal[1];
            }
        }
        return getVars;
    }
        
        
    // console.log(   GetParams('myTargetScript')   );

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文