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",
},
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>
If you want to check if the string is null just do if(previewImage == "") { /* image is null, do stuff */ }
but if you want to check if the image actually exists I would suggest doing a GET request via AJAX and check the HTTP response, eg: (jQuery):
$.ajax({
url: "http://123.201.137.238:6060/feed/videoplay/Jackie.png",
cache: false,
error: function(){
alert("image doesn't exist!");
}
});
But it would be "nicer" to do this server side if possible.
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.