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

大城市里の小女人 提交于 2019-12-07 23:31:27

问题


On the client side using jQuery, I want to know if I can just check if a link URL is valid (i.e. doesn't return a 404). This link points to another domain, so if I just use $.get() then I end up with a permission issue. I remember reading something about using a JSONP request, but I don't remember.


回答1:


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'.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2119680/use-jquery-to-check-if-a-url-on-another-domain-is-404-or-not

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