如何将脚本 src 文件的输出字符串重定向到 javascript 中的变量

How to redirect output string of script src file to a variable in javascript

我花了几个小时来寻找一个看似简单的问题,并尝试了在这里和其他地方找到的一些东西,但无法回答这个问题。我 运行 一个广播电台,服务器以简短的脚本输出当前歌曲的名称。脚本是

    <script type="text/javascript" src="http://cdn.voscast.com/stats/display.js?key=33d86e1438d74956b30a556c434a952e&stats=songtitle"></script>

并且工作正常。我想要的是与 Linux > 或 >> 运算符等效的东西,这样我就可以将显示在屏幕上的数据存储到一个变量中,这样我就可以在其他地方使用它。对不起,如果这是如此基本,但我已经尝试了很多不同的事情,只需要一些特定的简单代码来解决这个问题。谢谢

使用 jQuery 尝试类似的操作。它是您问题的完整解决方案。

<html>
<head>

  <!-- This includes the jQuery library you need to extract the song name -->
  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>

  <!-- This is the script you want the song name from -->  
  <script type='text/javascript' src="https://cdn.voscast.com/stats/display.js?key=33d86e1438d74956b30a556c434a952e&stats=songtitle"></script>

</head>
<body>

<script type='text/javascript'>
    $(window).load(function(){
        $('div').filter(function() {
            return /^.{13}/.test(this.id);
        }).each(function() {

            $(this).hide(); // Hide the song name here

            // Assign the name to a variable as you requested
            var songName = this.innerHTML;

            // Just for a demonstration
            alert( songName );

            // Do what you like with the song name here ...
        });
    });
</script>

</body>
</html>

加载 JavaScript 文件时,它会打印 div 并用歌曲名称填充它。 div id 看起来是随机生成的 13 个字符的字符串。您可以使用 jQuery 选择过滤器访问 div - /^.{13}/.test(this.id) 部分。