2010-09-05 67 views
4

我現在有這個jQuery代碼,它工作正常。當用戶點擊提交按鈕時它做了什麼,它會隱藏表單,顯示加載器,然後將數據提交到鏈接並將輸出加載到iframe中。如何檢查iframe是否無法加載? jQuery的?

$(document).ready(function() { 

$("#xxx_form").validate({ 
    submitHandler: function() { 
     $('#input_form').hide('slow'); 
     $('#loader').show('slow'); 
     form.submit(); 
    } 
}); 

$("#xxx_frame").load(function(){ 
    $('#loader').hide('slow'); 
    $('#history').show('slow'); 
    $('#xxx_frame').show('slow'); 
}); 

});

這工作正常。我需要的是如何檢查iframe加載是否正常。在測試期間,他們是iframe超時或發生無法連接到服務器的錯誤。由於ISP失敗。現在我需要檢查這種錯誤,我該怎麼做?

回答

1

據我所知,沒有辦法測試iframe中的錯誤。還有就是.error()事件,但根據文檔中的註釋:

使用.error()的iframe似乎永遠不會觸發(即使.load()將觸發一個成功的iframe中加載)。

也許你需要實現某種使用​​事件超時自己:如果負載事件(表示成功)不火之內,也就是說,五秒鐘承擔錯誤。

+5

負載事件將觸發即使在IE9的錯誤。 – jcoffland 2013-01-22 01:36:40

0

嘗試...

HTML:

<iframe id="box" ... 

JQUERY:

$('#box').bind('error', function() { 
    alert("loaded error"); 
} 

編輯:存在多個命令綁定負荷錯誤

0

末到派對,但我已經設法破解它:它不檢測iFrame是否正確加載,但它會檢測服務器是否可以訪問。爲了您的使用,您可以翻轉邏輯,並在服務器負載成功後隱藏某些內容。首先,我想做一個AJAX調用來測試網站a)是否存在以及b)是否允許跨源調用,但最初它並不適用於我,因爲我使用過jQuery。它完美,如果你做一個XMLHttpRequest:

var url = http://url_to_test.com/ 
var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status != 200) { 
     console.log("iframe failed to load"); 
    } 
}; 
xhttp.open("GET", url, true); 
xhttp.send(); 

編輯:
所以這種方法效果好,但它有很多的假陰性(拿起了很多的東西,會在iframe顯示)由於交叉來源malarky。我解決這個問題的方式是在服務器上執行CURL/Web請求,然後檢查a)網站是否存在,以及b)如果標頭已設置x-frame-options

如果您運行自己的網絡服務器,這不是問題,因爲您可以自己創建API調用。

我在node.js中實現:

app.get('/iframetest',function(req,res){ //Call using /iframetest?url=url - needs to be stripped of http:// or https:// 
    var url = req.query.url; 
    var request = require('https').request({host: url}, function(response){ //This does an https request - require('http') if you want to do a http request 
     var headers = response.headers; 
     if (typeof headers["x-frame-options"] != 'undefined') { 
      res.send(false); //Headers don't allow iframe 
     } else { 
      res.send(true); //Headers don't disallow iframe 
     } 
    }); 
    request.on('error',function(e){ 
     res.send(false); //website unavailable 
    }); 
    request.end(); 
}); 
相關問題