开发者

Change image source if file exists

I have http://jsfiddle.net/rcebw/3/

The point of this is I will have numerous of these inlinediv divs. Each one has 2 divs inside it, one which holds an image and one which holds a link. These are generated dynamically from a list of the subsites on another site.

What I want it to do is check each div with the class inlinediv. Get the inner text of the link in div iconLinkText and search for a file with that name at the site. (http://www.mojopin.co.uk/images/ for this test.) If it exists then change the image src to it.

开发者_如何学JAVA

I am probably taking the absolutely wrong route for this but I can't seem to get it to work. When testing it can't even find the inlinediv div! Says it's null.

I'm pretty new to jQuery but does anyone have any advice? (I don't even know if I've explained myself well!)


You don't have to use AJAX to do this, since you can hot-link images from other domains without any restrictions. Here's how you can check if an image exists:

function checkImage(src) {
  var img = new Image();
  img.onload = function() {
    // code to set the src on success
  };
  img.onerror = function() {
    // doesn't exist or error loading
  };

  img.src = src; // fires off loading of image
}

Here's a working implementation http://jsfiddle.net/jeeah/


Here is a modern Promise based way, which will return a Promise with a boolean value.

function imageExists(src) {
    return new Promise((resolve, reject) => {
      var img = new Image();
      img.onload = function () {
        resolve(true);
      }
      img.onerror = function (error) {
        resolve(false);
      }
      img.src = src;
    })
}


const imagePath = "http://www.google.com/images/logo_sm.gif";
imageExists(imagePath).then(doesExist => {
  console.log('doesImageExist', doesExist);
});
  

You can of course use async/await syntax for this.

const doesImageExist = await imageExists(imagePath);


The Same Origin Policy prevents you from making AJAX requests to other domains. Unless you're running this on "http://www.mojopin.co.uk", this code won't work.


You cannot solve this problem only with jQuery: The Same Origin Policy wont allow you to make requests to third web sites.

The easiest solution is to implement a service on your server that proxies the requests to the external website.

Basically if your website is on

http://www.foo.bar

then you create

http://www.foo.bar/scheckscript.php (for example)

that you can query with the url you need

http://www.foo.bar/scheckscript.php?url=http%3A//www.third.com

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜