如果未正确加载,则隐藏iframe [英] Hide iframes if not correctly loaded

查看:100
本文介绍了如果未正确加载,则隐藏iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个iframe指向我网页上的外部网站。如果这些服务被中断或更改,我想隐藏这些iframe,而不是在我的页面上显示错误消息。
如果iframe已正确加载,有没有办法在Javascript中查找?
我添加了一个隐藏iframe的类,然后在iframe准备就绪后用jQuery删除它,如下所示:

I have several iframes pointing to external websites on my page. In case those services are interrupted or changed, I would like to hide those iframes instead of displaying an error message on my page. Is there any way to find out in Javascript if the iframe has been loaded correctly? I added a class to hide the iframe and then remove it with jQuery when the iframe is ready, like this:

$('#widget').ready(function () {
    $('#widget').removeClass('hidden');
});

当我在iframe src中放入无效网址时,它仍会删除隐藏的类,显示错误的iframe 。
我的问题是两个:

It still removes the hidden class when I put an invalid URL in the iframe src, showing the error iframe. My questions are two:


  • 如果iframe已正确加载,如何才能运行该函数?

  • 我没有使用$('#widget')准备好,而是想使用$('iframe')。准备好立刻定位所有iframe;如果我这样做,如何在函数内部引用加载的特定iframe?

谢谢!

推荐答案

您的问题可归结为:


怎么能我检查网址是否存在且网站是否存在Javascript?

how can I check if an URL exists and the website is alive from Javascript ?

答案分为:


  • 对于内部网址,请使用AJAX并检查响应代码:如果它是 2xx 3xx (例如200或302),没关系。如果 4xx 5xx (例如404或500)则不好。详细了解类似答案

  • For internal URLs, use AJAX and check the response code: if it's 2xx or 3xx (eg 200 or 302), it's fine. If it's 4xx or 5xx (eg. 404 or 500) it's bad. Read more on a similar answer.

外部网址,由于名为同源政策

由于您似乎指向外部网址,因此这里是我的建议:

Since it seems you are pointing to external URLs, here is my suggestion:

根据服务器端技术,创建服务器端组件(Servlet,RESTful WebService,Struts2操作等等......根据您的喜好...您正在使用)为您执行检查,并返回带有数据(如果有)的流式响应以及可以检查错误的HTTP响应代码。然后从< iframe> 调用您的组件网址。

Create a server-side component (a Servlet, a RESTful WebService, a Struts2 action, etc... whatever you prefer, according to the server side technology you are using) that perform the check for you, and return a streamed response with the data (if any) and the HTTP response code that you can check for errors. Then from the <iframe>s call your component URL.

这篇关于如果未正确加载,则隐藏iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆