简体   繁体   English

jQuery检查外部链接

[英]jQuery check external link

Using Javascript or jQuery, how can I check if an external link is available? 使用Javascript或jQuery,如何检查外部链接是否可用?

An $.ajax() call is not available as it violates SOP (same problem as here ). $.ajax()调用不可用,因为它违反了SOP (与此处相同的问题)。 I have read about JSONP , but I would like to know if there is a more straight solution, as I don't want to load any data from the external server; 我已经阅读了有关JSONP的文章 ,但是我想知道是否还有一个更直接的解决方案,因为我不想从外部服务器加载任何数据。 what I need is only to check if it is reachable. 我需要的只是检查它是否可以到达。


EDIT (answer) 编辑(答案)

I solved it with the following code: 我用以下代码解决了它:

$.ajax({url: 'http://www.example.com',
        type: 'GET',
        dataType: 'jsonp',
        complete: function(jqXHR, textStatus) {
                console.log(jqXHR.status);  // '200' = url reachable
        },
        timeout: 2000
});

The only problem now is that I get a Parse error , but in any case it can be checked if the external link is working. 现在唯一的问题是我收到了Parse error ,但是无论如何都可以检查外部链接是否正常工作。

You could use YQL to check if a URL is available via its JSONP interface. 您可以使用YQL来通过其JSONP接口检查URL是否可用。

YQL Console . YQL控制台

Do you have access to server side languages? 您可以访问服务器端语言吗? You could use AJAX to call a local file which uses something like PHP to check the external address. 您可以使用AJAX调用本地文件,该文件使用类似PHP的文件来检查外部地址。

If you need help with the PHP part, have a look at http://www.catswhocode.com/blog/amazing-things-to-do-with-php-and-curl 如果您需要有关PHP部分的帮助,请访问http://www.catswhocode.com/blog/amazing-things-to-do-with-php-and-curl

Yes, in browsers that support flash you can use this plugin. 是的,在支持Flash的浏览器中,您可以使用插件。 It has the same api as native xhr. 它具有与本机xhr相同的api。 Further if there is no flash plugin in browsers you still can access the other domain. 此外,如果浏览器中没有Flash插件,您仍然可以访问其他域。 In some browsers if your target domain response has the following headers there will not be an error. 在某些浏览器中,如果您的目标域响应具有以下标头,则不会出现错误。

Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, *

Replace * with appropriate domains. 用适当的域替换*。

All above techniques are applicable only if the second domain is under your control. 以上所有技术仅在您控制第二个域时适用。 If not then you have to use a proxy as Jleagle said. 如果没有,那么您必须使用Jleagle所说的代理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM