简体   繁体   中英

How can I retrieve image error code using JavaScript or jQuery?

I am changing the src attribute of an image element. If there's an error I want to know the error status code.

You could adapt this source example on mdn web docs. If you change the src attribute programmatically and need to check first if it gives an error code, it could do the job. Here a draft, I hope this is going to help you.

 let changesrc = (newsrc) => { const myImage = document.getElementById('testimg'); const myRequest = new Request(newsrc); fetch(myRequest).then((response) => { console.log(response.status); if(response.status == "200") { response.blob().then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); } }); };
 <button onclick="changesrc('https://picsum.photos/200');">test ok</button> <button onclick="changesrc('https://picsum.photos/noway');">test not ok</button> <img id='testimg' src="https://picsum.photos/200">

You can use Image API in Javascript, for know when image load fail:

function mountImage(src) {
  const img = new Image();
  
  img.src = src;

  img.onload = () => {
    // image loaded
  }

  img.onerror = () => {
     // image fail load
  }



}

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