如何每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 fromother.php.- HTML Parsing: We use a temporary
<div>to load the fetched HTML, then usequerySelectorto pull the text inside the#link1span—this is a safe way to parse HTML fragments in JS. - Interval Trigger:
setIntervalruns 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
srcif the new link is different from the current one, which prevents unnecessary image reloads when the link hasn’t changed.
Quick Notes:
- Ensure
other.phpis in the same directory asindex.php, or adjust the path infetch()if it’s stored elsewhere (e.g.,fetch('./includes/other.php')). - If you need support for older browsers (like IE), replace
fetchwithXMLHttpRequest—but Fetch API is supported in all modern browsers, so this shouldn’t be an issue for most use cases.
内容的提问来源于stack exchange,提问作者Wong Tony
相关产品推荐
相关产品推荐

