Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a content in URL (Javascript)

I have URLs in JSON feed n each URL contains one image. I want to validate those URLs which have image or not (NULL). How to validate this using javascript. since I'm a beginner, i don't know, how to validate this. thanks

      JSON feed with image n NULL
        {

         previewImage:"http://123.201.137.238:6060/feed/videoplay/Jackie.png",

        }, 
        {

        previewImage:"http://www.snovabits.net/feed/ImageMI/WarCraft.jpg",

        },
like image 877
FreshBits Avatar asked Nov 13 '22 13:11

FreshBits


1 Answers

Interesting question!

Try to add the images to a div (use jQuery, the div can be hidden using display:none;).
Then test the properties of the images regularly (use a setInterval loop) whether they indicate a successful load. Define some timeout after which the setInterval will kill itself.

This property works for testing successful img load in Chrome and Firefox:

naturalHeight != 0

This property works for testing successful img load in IE7,8,9:

fileCreatedDate != ''

Test both to make it work in all major browsers.

Here is a fiddle to see how the props change in 10ms steps during the load process. Try it in different browsers!:
http://jsfiddle.net/xGmdP/

In Chrome and FF you can even replace the timeout for the setInterval loop by checking the complete property of all images. But unfortunately this does not work in IE (complete always stays false in IE for images that cannot be loaded).

Finally here is the complete code of the fiddle:

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js" type="text/JavaScript"></script>
  <script type="text/JavaScript">
    $(function(){
      $('#images').prepend('<img id="img1" src="http://123.201.137.238:6060/feed/videoplay/Jackie.png">')
      $('#images').prepend('<img id="img2" src="http://www.snovabits.net/feed/ImageMI/WarCraft.jpg">')
      setInterval(test, 10);
    })

    function test(){
      var props=['naturalHeight', 'complete', 'fileCreatedDate', 'clientHeight', 'offsetHeight', 'nameProp', 'sourceIndex'];
      for(i in props){
        var pr = props[i];
        $('#testresults').append('1:'+pr+' = ' + $('#img1').prop(pr)+'<br>');
        $('#testresults').append('2:'+pr+' = ' + $('#img2').prop(pr)+'<br>');
      }
      $('#testresults').append('---<br>');
    }
  </script>
</head>
<body>
  <div id="images"><div>
  <div id="testresults"></div>
</body>
</html>
like image 108
Jpsy Avatar answered Nov 16 '22 02:11

Jpsy