问题描述
我的页面中有一个 iframe
。如果 iframe
未加载,请将其设为 alert
消息 pdf未找到,如果 iframe
确实加载,它应该 alert
pdf打开。
有人知道如何做到这一点吗? 所以,这个想法是使用Ajax请求来测试URL。与< iframe>
元素不同,它只提供一个加载处理程序,Ajax请求使您可以绑定成功和错误处理程序。
当然,Ajax请求受同源策略限制(除非Web服务器启用CORS),但是您声明PDF位于同一个域中,所以不应该存在任何问题。
另外,您声明您使用Mootools库 - 我使用jQuery,因此我只能为您提供jQuery解决方案,但由于我们正在制作一个带有成功和错误处理程序的简单Ajax请求,你应该能够很容易地基于我的jQuery解决方案重新创建一个Mootools解决方案。
因此,给定一个iframe和URL: var iframe = $('#iframe')[0]; //引用IFRAME元素
var url ='files / document1.pdf';
Ajax请求:
$。get(url,function(){
iframe.onload = function(){alert('PDF opened!');};
iframe.src = url ;
})。error(function(){alert('PDF not found');});
成功演示:
错误演示:
因此,如果Ajax请求触发错误事件,我们只需立即提醒未找到消息。但是,如果Ajax请求触发成功事件,我们会为我们的IFRAME元素分配一个加载处理程序(此加载处理程序将最终警告已加载消息),并将URL设置为其<<$手动添加c $ c> src 属性。
I have a iframe
in my page. If the iframe
doesn't load, want it to alert
the message "pdf not found" and if the iframe
does load, it should alert
"pdf opened".
Does anyone know how to achieve that?
So, the idea is to use an Ajax-request to "test" the URL. Ajax-requests enable you to bind "success" and "error" handlers - unlike <iframe>
elements which only provide a "load" handler.
Of course, Ajax-requests are restricted by the Same Origin Policy (unless the web-server enables CORS), but you stated that the PDF is on the same domain, so there shouldn't be any issues.
Also, you stated that you use the Mootools library - I use jQuery, so I can only provide you with a jQuery solution, but since we're making a simple Ajax-request with "success" and "error" handlers, you should be able to recreate a Mootools solution based on my jQuery solution easily.
So, given an iframe and an URL:
var iframe = $( '#iframe' )[0]; // reference to IFRAME element
var url = 'files/document1.pdf';
The Ajax-request:
$.get( url, function () {
iframe.onload = function () { alert( 'PDF opened!' ); };
iframe.src = url;
}).error( function () { alert( 'PDF not found' ); });
Success-demo: http://jsfiddle.net/CZWdL/1/show/
Error-demo: http://jsfiddle.net/CZWdL/2/show/
So, if the Ajax-request triggers an "error" event, we simply alert the "Not found" message immediately. If, however, the Ajax-request triggers a "success" event, we assign a "load" handler to our IFRAME element (this "load" handler will eventually alert the "Loaded" message), and set the URL to its src
property manually.
这篇关于想要在iframe不加载或加载时调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!