Fetch API调用随机图片 - 代码示例

注意:Fetch API调用随机图片API的代码示例。

Fetch API实现代码

// 使用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();

完整的HTML页面示例

随机图片API测试

随机图片API测试

常见问题与解决方案:

  1. 缓存问题:添加时间戳参数(如?t=${timestamp})以确保每次获取新图片
  2. CORS问题:确保PHP API设置了正确的CORS头(Access-Control-Allow-Origin)
  3. 错误处理:实现完整的错误处理流程,包括HTTP错误和图片加载错误
  4. 资源清理:使用URL.revokeObjectURL()在不需要时释放临时URL

使用说明:

1. 将上述代码部署到支持PHP的Web服务器上

2. 确保random_image_api插件已正确安装且config.php配置正确

3. 在浏览器中访问HTML页面即可测试随机图片获取功能