Use jQuery to check if a URL on another domain is 404 or not?

依然范特西╮ 提交于 2019-12-06 07:08:32

I found a solution that seems to work (using YQL):

$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
            "q=select%20*%20from%20html%20where%20url%3D%22"+
            encodeURIComponent(url)+
            "%22&format=xml'&callback=?",
    function(data){
      if(data.results[0]){
        // do whatever
      } 
    }
  );

Assumes the URL you want to check is in the variable 'url'.

JSONP works if the server you are calling on can return JSONP formatted response. Which basically means a script that calls a callback function on your page after getting loaded. see http://en.wikipedia.org/wiki/JSON#JSONP

In your case it won't work unless the other site is willing to cooperate or you have a proxy script on your own site.

If you want your script to work with sites not under your control, your best bet will be to use a proxy or a iframe hack.

You can't make a request like that to another domain. That is a security feature in the browser. You may have to try doing something in an iframe or something and checking that.

jsonp wont do you much...

What you should do is create a local proxy easily on your server using your favorite language that'll simply load the url you pass to it and return the response code. Then, use jquery ajax to load up the proxy page with the url you want to test.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!