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

如何每5秒从other.php自动刷新index.php中img标签的src链接

Solution: Auto-refresh Image Source Every 5 Seconds

Got it, here's a clean, vanilla JavaScript implementation to pull the image link from other.php and update your img tag's src automatically on a 5-second loop:

Step 1: Update Your index.php

Add this code to your index.php page (place it right before the closing </body> tag for optimal loading):

<img id="img1" class="imgNews" src="https://example.com/car.jpg">

<script>
// Grab the image element we need to update
const targetImage = document.getElementById('img1');

// Function to fetch the latest link and update the image
function refreshImageSource() {
  // Send a request to other.php to get its content
  fetch('other.php')
    .then(response => {
      if (!response.ok) {
        throw new Error('Failed to fetch the image link');
      }
      return response.text();
    })
    .then(htmlContent => {
      // Parse the fetched HTML to extract the link from the span
      const tempContainer = document.createElement('div');
      tempContainer.innerHTML = htmlContent;
      const newImageLink = tempContainer.querySelector('#link1').textContent.trim();
      
      // Only update the src if the link changed (avoids redundant reloads)
      if (targetImage.src !== newImageLink) {
        targetImage.src = newImageLink;
      }
    })
    .catch(error => {
      console.error('Error updating image:', error);
    });
}

// Run once immediately so the image updates on page load
refreshImageSource();

// Set up the 5-second interval to keep refreshing
setInterval(refreshImageSource, 5000);
</script>

How This Works:

  • fetch('other.php'): Sends a simple request to grab the full HTML content from other.php.
  • HTML Parsing: We use a temporary <div> to load the fetched HTML, then use querySelector to pull the text inside the #link1 span—this is a safe way to parse HTML fragments in JS.
  • Interval Trigger: setInterval runs our refresh function every 5000 milliseconds (5 seconds). We also call the function right away so users don’t have to wait 5 seconds for the first update.
  • Optional Efficiency Check: We only update the src if the new link is different from the current one, which prevents unnecessary image reloads when the link hasn’t changed.

Quick Notes:

  • Ensure other.php is in the same directory as index.php, or adjust the path in fetch() if it’s stored elsewhere (e.g., fetch('./includes/other.php')).
  • If you need support for older browsers (like IE), replace fetch with XMLHttpRequest—but Fetch API is supported in all modern browsers, so this shouldn’t be an issue for most use cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:56