// 使用Fetch API获取随机图片
function fetchRandomImage(category = 'all') {
// 构建API URL
const apiUrl = `https://www.pengjianwei.com/plugins/random_image_api/index.php${category !== 'all' ? `?category=${category}` : ''}`;
// 添加时间戳参数以防止缓存
const timestamp = new Date().getTime();
const fullUrl = apiUrl.includes('?') ?
`${apiUrl}&t=${timestamp}` :
`${apiUrl}?t=${timestamp}`;
fetch(fullUrl)
.then(response => {
// 检查响应状态
if (!response.ok) {
// 尝试解析JSON错误响应
return response.json()
.catch(() => {
// 如果无法解析为JSON,创建一个通用错误
return { message: `HTTP错误! 状态码: ${response.status}` };
})
.then(error => Promise.reject(error));
}
// 检查响应是否为图片
const contentType = response.headers.get('content-type');
if (contentType && contentType.startsWith('image/')) {
return response.blob();
} else {
// 如果不是图片,尝试解析为JSON错误
return response.json().then(data => Promise.reject(data));
}
})
.then(blob => {
// 创建图片URL并显示
const imageUrl = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = imageUrl;
img.alt = '随机图片';
// 图片加载完成后释放临时URL
img.onload = () => {
document.body.appendChild(img);
// 清理:当不再需要时释放ObjectURL
// URL.revokeObjectURL(imageUrl);
};
img.onerror = () => {
throw new Error('图片加载失败');
};
})
.catch(error => {
console.error('获取随机图片失败:', error);
alert('获取图片失败: ' + (error.message || JSON.stringify(error) || '未知错误'));
});
}
// 调用函数获取随机图片
fetchRandomImage();
使用说明:
1. 将上述代码部署到支持PHP的Web服务器上
2. 确保random_image_api插件已正确安装且config.php配置正确
3. 在浏览器中访问HTML页面即可测试随机图片获取功能