简体   繁体   中英

How to get status code from an image url? Javascript

How would you get a status code from an image url. If the image status code is 404, I'd like to replace it with something else.

You can use onload and onerror events.

<script type="text/javascript">
  function onImageLoad() {
    alert("imgOne is loaded.");
  }

  function onImageLoadError() {
    alert("imgTwo is not loaded.");
  }
</script>
<img src="http://via.placeholder.com/350x150" id="imgOne" onload="onImageLoad(this);" />
<img src="http://via1.placeholder.com/350x150" id="imgTwo" onerror="onImageLoadError(this);" />

JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM