jQuery: Check if image exists

后端 未结 6 693
予麋鹿
予麋鹿 2020-11-27 17:20

I\'m loading an image path via jQuery $.ajax and before showing the image I\'d like to check if it in fact exists. Can I use the image load/ready event or something similar

6条回答
  •  感情败类
    2020-11-27 18:20

    Try:

    function urlExists(testUrl) {
     var http = jQuery.ajax({
        type:"HEAD",
        url: testUrl,
        async: false
      })
      return http.status;
          // this will return 200 on success, and 0 or negative value on error
    }
    

    then use

    if(urlExists('urlToImgOrAnything') == 200) {
        // success
    }
    else {
        // error
    }
    

提交回复
热议问题