Posted By

sergiomas on 07/05/06


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

xaviaracil
vali29
umang_nine


Comprobar con AJAX si existe una imagen


 / Published in: HTML
 

visto en http://www.moddedup.com/imageexists/imageexists.html

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <title>Using AJAX to check if a file exists</title>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
  4. <script type="text/javascript">
  5. var req, image, warning, imagepath;
  6.  
  7. function d(o)
  8. {
  9. return document.getElementById(o);
  10. }
  11.  
  12. function loadimage(_imagepath)
  13. {
  14. image = d("image");
  15. image.style.display = "none";
  16.  
  17. imagepath = _imagepath;
  18.  
  19. warning = d("warning");
  20. warning.innerHTML = "Loading ...";
  21.  
  22. req = getreq();
  23. req.onreadystatechange = imagexists;
  24. req.open("get", imagepath, true);
  25. req.send(null);
  26. }
  27.  
  28. function imagexists()
  29. {
  30. if(req.readyState == 4)
  31. {
  32. if(req.status == 200)
  33. {
  34. warning.innerHTML = "Image exists";
  35. image.style.display = "block";
  36. image.src = imagepath;
  37. }
  38. else
  39. {
  40. warning.innerHTML = "Image does not exist";
  41. image.style.display = "none";
  42. }
  43. }
  44. }
  45.  
  46. function getreq()
  47. {
  48. if(window.XMLHttpRequest)
  49. return new XMLHttpRequest();
  50. else if(window.ActiveXObject)
  51. return new ActiveXObject("Microsoft.XMLHTTP");
  52. }
  53.  
  54. <style type="text/css">
  55. * { font-family: Verdana, Arial, sans-serif; }
  56. body { background-color: #FFF; }
  57. h1 { font-size: 14px; }
  58. #warning { margin: 10px; }
  59. #img { border: 1px solid #CCC; padding: 3px; margin: 10px; }
  60. </head>
  61.  
  62.  
  63. <h1>Check an image exists with AJAX</h1>
  64.  
  65. <input type="button" value="Load real image" onclick="loadimage('IMAG0272.jpg');" />
  66. <input type="button" value="Load fake image" onclick="loadimage('5hhhh_thumb.jpg');" />
  67.  
  68. <div id="warning"></div>
  69. <img id="image" src="blank.jpg" style="display: none;" alt="" />
  70.  
  71. </body>
  72. </html>

Report this snippet  

You need to login to post a comment.