【问题标题】:Specify if image of url leads to null指定 url 的图像是否导致 null
【发布时间】:2018-05-07 19:16:53
【问题描述】:

我正在设计一个在服务器上显示任何歌曲图标的网站。我创建了一个 php 文件,它返回歌曲的图像(如果存在)。我的 HTML 代码:

<img src="/image.php?song=SongName" width="100" height="100">

如果给定歌曲有翻唱图标,则 img 元素会显示该图标。如果没有,我会得到一个 100x100 的空图像框。

现在,我想在javascript中指定,如果url地址:'/image.php?song=SongName'返回null(如果歌曲上没有图像封面),以隐藏img。如何实现?

谢谢。

PS。到目前为止我尝试过的代码(img url 格式有一点 php):

var picElement = document.getElementById("picture");
picElement.src = "/image.php?song=$nameFile";
if(picElement.src == null){
    picElement.style.display = "none";
}else if(picElement.src !=null){
    picElement.src = "/image.php?song=$nameFile";
    picElement.style.height = "20vh";
    picElement.style.width = "20vh";
    picElement.style["boxShadow"] = "3px 3px 10px 1px #e2b674";
}

image.php下的php代码:

<?PHP
$song= $_GET["song"];
require_once("getID3-1.9.15/getid3/getid3.php");
$Path= .$song.".mp3";

$getID3 = new getID3;
$OldThisFileInfo = $getID3->analyze($Path);
if(isset($OldThisFileInfo['comments']['picture'][0]))
{
    header('Content-Type: ' . $OldThisFileInfo['comments']['picture'][0]['image_mime']);
    echo $OldThisFileInfo['comments']['picture'][0]['data'];
    die;
}?>

【问题讨论】:

  • 所以它返回错误?比使用 onerror
  • 您是如何尝试自己解决这个问题的?有示例代码吗?
  • 如果图像不存在,我希望它是 404,并且 onerror 处理程序可以将图像路径设置为另一个图像 src。如果您只是返回一个空白图像,那么解决问题会变得更加困难。

标签: javascript php image error-handling


【解决方案1】:

如果您想仅使用标记来处理显示默认图像,您可以为每个图像添加属性onerror="this.src='/image.php?song=Default'" 或类似属性:

<img src="/image.php?song=SongName" onerror="this.src='/image.php?song=Default'" width="100" height="100"/>

这假定/image.php 在找不到图像时会正确返回 404 错误,而不是显示默认图像本身。

更新

按照您的 PHP 代码,您可能只想将歌曲名称回显到 HTML 而不是 JavaScript:

<img src="/image.php?song=<?PHP echo $nameFile; ?>" onerror="this.style.display='none'" width="100" height="100" />

【讨论】:

  • 谢谢它的工作!但是为什么会触发onerror事件呢?
  • @Nick 因为当if(isset($OldThisFileInfo['comments']['picture'][0])) 为假时,您的/image.php 不会返回图像数据
猜你喜欢
  • 1970-01-01
  • 2019-01-16
  • 2011-03-28
  • 2011-04-10
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 2016-03-17
相关资源
最近更新 更多