You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从PHP页面获取歌曲标题并导入JavaScript脚本?

How to Import Song Title from PHP to JavaScript

Hey HermanF, no worries—let's get that song title from your songtitle.php page into your JavaScript code. Here are a few straightforward methods you can use:

Method 1: Use the Fetch API (Modern Approach)

This is the cleanest way for modern browsers. It lets you make an HTTP request to your PHP page and grab the title directly:

// Fetch the song title from the PHP page
fetch('http://blaffdf.nl/songtitle.php')
  .then(response => response.text()) // Get the raw text response (since your PHP just outputs the title)
  .then(songTitle => {
    // Now you can use the songTitle variable anywhere in your code
    console.log('Current song:', songTitle);
    // Replace your old line with this to assign the title to str
    var str = songTitle;
  })
  .catch(error => {
    console.error('Error fetching song title:', error);
  });

Method 2: XMLHttpRequest (For Older Browser Compatibility)

If you need to support older browsers that don't have Fetch API support, use this classic approach:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://blaffdf.nl/songtitle.php', true);

xhr.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // Success: extract the song title from the response
    var songTitle = this.responseText;
    console.log('Current song:', songTitle);
    var str = songTitle;
  } else {
    console.error('Server returned an error');
  }
};

xhr.onerror = function() {
  console.error('Connection error when fetching song title');
};

xhr.send();

Method 3: Embed PHP Variable Directly (If JS is in the Same PHP File)

If your JavaScript code lives inside a PHP file (not a separate .js file), you can directly inject the song title value into your JS:

<?php
// Grab the song title from your PHP endpoint
$songTitle = file_get_contents('http://blaffdf.nl/songtitle.php');
?>

<script>
// Use addslashes to avoid issues with quotes in the song title
var str = "<?php echo addslashes($songTitle); ?>";
console.log('Current song:', str);
</script>

Important Notes:

  • CORS Check: If your JavaScript runs on a different domain than blaffdf.nl, you'll need to add CORS headers to songtitle.php to allow the request. Add this at the top of your PHP file:
    header("Access-Control-Allow-Origin: *"); // Replace * with your specific domain for better security
    
  • Prevent Caching: If the song title updates frequently, add cache-control headers to songtitle.php to stop browsers from storing old titles:
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Pragma: no-cache");
    header("Expires: 0");
    

内容的提问来源于stack exchange,提问作者HermanF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:05:50