MENU

php版 简洁好看的随机图片 支持ajax刷新 自适应

January 8, 2025 • Read: 35 • More

代码功能

使用 PHPJavaScript 实现的随机图片展示页面,支持Ajax刷新加载图片。

目录结构

/your-project-directory
    ├── index.php
    ├── get_random_image.php
    └── images.txt

images.txt

每行包含一个图片地址,示例:

https://img0.baidu.com/it/u=4245391110,2737142142&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422
http://img0.baidu.com/it/u=4096475799,483816106&fm=253&app=138&f=JPEG?w=800&h=1422

get_random_image.php

这个新文件将负责生成并返回随机图片的URL。

<?php
session_start();
 
function getRandomImage() {
    $imageFile = 'images.txt';
    $imageLines = file($imageFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    if (empty($imageLines)) {
        die('No images found in images.txt');
    }
    
    $imageCount = count($imageLines);
    $previousRandomIndex = isset($_SESSION['previousRandomIndex']) ? $_SESSION['previousRandomIndex'] : -1;
    
    // Generate a new random index, avoiding the previous one if possible
    $randomIndex;
    do {
        $randomIndex = rand(0, $imageCount - 1);
    } while ($randomIndex == $previousRandomIndex);
    
    // Update the session variable with the new random index
    $_SESSION['previousRandomIndex'] = $randomIndex;
    
    // Return the random image URL
    echo json_encode(['image_url' => $imageLines[$randomIndex]]);
    exit;
}
 
// Call the function to get and return the random image
getRandomImage();

index.php

这个文件将包含HTML、CSS和JavaScript来显示图片和处理Ajax请求。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Image Display with Ajax</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
            text-align: center;
        }
        img {
            max-width: 100%;
            max-height: 80vh;
        }
        button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <img id="randomImage" src="" alt="Random Image will appear here">
    <button id="changeImageButton">点击换一张</button>

    <script>
        document.getElementById('changeImageButton').addEventListener('click', function() {
            fetch('get_random_image.php')
                .then(response => response.json())
                .then(data => {
                    if (data && data.image_url) {
                        document.getElementById('randomImage').src = data.image_url;
                    } else {
                        alert('Failed to load a new image.');
                    }
                })
                .catch(error => {
                    console.error('Error fetching new image:', error);
                    alert('An error occurred while fetching a new image.');
                });
        });
    </script>
</body>
</html>

代码解释

  1. get_random_image.php:这个脚本负责生成随机图片的URL,并将其作为JSON响应返回。它使用会话变量来避免连续生成相同的随机索引。
  2. index.php:HTML页面包含一个<img>元素来显示图片,以及一个<button>元素来触发Ajax请求。JavaScript使用fetch API来异步请求get_random_image.php,并在成功获取新图片的URL后更新<img>元素的src属性。

增加icon图标

<!-- 在<head>标签内添加Font Awesome的CDN链接 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Image Display with Ajax</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* ...之前的样式... */

        /* 为按钮添加一些额外的样式来更好地显示图标 */
        #changeImageButton {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px; /* 图标和文本之间的间距 */
        }

        /* 可选的:为图标添加一些样式 */
        #changeImageButton i {
            font-size: 1.2em; /* 图标大小 */
        }
    </style>
</head>
<body>
    <img id="randomImage" src="" alt="Random Image will appear here">
    <!-- 修改按钮,添加Font Awesome图标 -->
    <button id="changeImageButton">
        <i class="fas fa-sync-alt"></i> <!-- 刷新图标 -->
        点击换一张
    </button>

    <script>
        // ...之前的JavaScript代码...
    </script>
</body>
</html>

修改后index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Image Display with Ajax</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
            text-align: center;
        }
        img {
            max-width: 100%;
            max-height: 80vh;
        }
        button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
        /* 为按钮添加一些额外的样式来更好地显示图标 */
        #changeImageButton {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px; /* 图标和文本之间的间距 */
        }
 
        /* 可选的:为图标添加一些样式 */
        #changeImageButton i {
            font-size: 1.2em; /* 图标大小 */
        }
    </style>
</head>
<body>
    <img id="randomImage" src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="Random Image will appear here">
    <!-- 修改按钮,添加Font Awesome图标 -->
    <button id="changeImageButton">
        <i class="fas fa-sync-alt"></i> <!-- 刷新图标 -->
        点击换一张
    </button>
 
    <script>
        document.getElementById('changeImageButton').addEventListener('click', function() {
            fetch('get_random_image.php')
                .then(response => response.json())
                .then(data => {
                    if (data && data.image_url) {
                        document.getElementById('randomImage').src = data.image_url;
                    } else {
                        alert('Failed to load a new image.');
                    }
                })
                .catch(error => {
                    console.error('Error fetching new image:', error);
                    alert('An error occurred while fetching a new image.');
                });
        });
    </script>
</body>
</html>

对于国内用户来说,访问位于国外的CDN资源(如:https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css)可能会遇到加载速度较慢的问题。为了解决这个问题,可以考虑使用国内的CDN镜像或者将Font Awesome下载到本地进行引用。

优化版index.php

  1. 增加加载状态显示:在加载新图片时,显示一个加载图标或文本,以提高用户体验。
  2. 错误处理优化:在加载图片失败时,提供更友好的错误提示。
  3. 代码结构优化:将JavaScript代码封装在一个函数中,以提高代码的可读性和可维护性。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Image Display with Ajax</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* 样式与之前相同 */
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
            text-align: center;
        }
        img {
            max-width: 100%;
            max-height: 80vh;
        }
        button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
        #changeImageButton {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        #changeImageButton i {
            font-size: 1.2em;
        }
        /* 新增加载状态样式 */
        #loadingOverlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none; /* 默认隐藏 */
        }
        #loadingOverlay i {
            font-size: 2em;
            color: white;
        }
    </style>
</head>
<body>
    <div id="loadingOverlay">
        <i class="fa-solid fa-spinner fa-spin"></i> <!-- 加载图标 -->
    </div>
    <img id="randomImage" src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="Random Image will appear here">
    <button id="changeImageButton">
        <i class="fa-solid fa-rotate-right"></i>
        点击换一张
    </button>
 
    <script>
        // 封装获取随机图片的函数
        function getRandomImage() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            loadingOverlay.style.display = 'flex'; // 显示加载状态
 
            fetch('get_random_image.php')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    loadingOverlay.style.display = 'none'; // 隐藏加载状态
                    if (data && data.image_url) {
                        document.getElementById('randomImage').src = data.image_url;
                    } else {
                        alert('Failed to load a new image. Please try again later.');
                    }
                })
                .catch(error => {
                    loadingOverlay.style.display = 'none'; // 隐藏加载状态
                    console.error('Error fetching new image:', error);
                    alert('An error occurred while fetching a new image. Please try again later.');
                });
        }
 
        // 为按钮添加点击事件监听器
        document.getElementById('changeImageButton').addEventListener('click', getRandomImage);
    </script>
</body>
</html>

附加事项(上面已经写了,可选)

get_random_image.php文件:确保该文件能够正确地从您的图片数据库中随机选择一张图片,并以JSON格式返回图片的URL。例如:

<?php
header('Content-Type: application/json');

// 假设您有一个包含图片URL的数组
$images = [
    'https://example.com/images/photo1.jpg',
    'https://example.com/images/photo2.jpg',
    // ... 更多图片URL
];

// 随机选择一张图片
$randomIndex = array_rand($images);
$randomImage = $images[$randomIndex];

// 返回JSON响应
echo json_encode(['image_url' => $randomImage]);
?>


Last Modified: January 14, 2025
Archives QR Code Tip
QR Code for this page
Tipping QR Code