2016-01-03 35 views
1

我想要做的是通過使用iframe從服務器端拉文件到客戶端。iframe和通過jquery附加事件

下面的代碼會收到一個帶有指向服務器上文件路徑的json字符串。如果文件存在,該文件被下載,如果失敗,它應該提醒我。警報功能不起作用。這是因爲我無法附加'加載'事件。 負載事件處理程序應該給我的iframe的內容,但不會發生。爲什麼?我在控制檯收不到任何東西。 var file_directory =「http:// localhost/test /」;

$.getJSON('http://localhost/file.php', function(data) { 
    for(index in data) { 
     if(data[index]=='.' || data[index]=='..') 
      continue; 

     console.log(file_directory+data[index]); 


      var frame= $('<iframe />'); // Create an iframe element 
      $('<iframe />', { 
       name: 'frame1', 
       id: 'frame1'+index, 
       src: file_directory+"d"+data[index]     
      }).appendTo('body'); 

      $('body').on('onload',frame,function() { 
       console.log(1); 
       try { 
       // Displays the first 50 chars in the innerHTML of the 
       // body of the page that the iframe is showing. 
       // EDIT 2012-04-17: for wider support, fallback to contentWindow.document 
       var doc = frame.contentDocument || frame.contentWindow.document; 
       console.log(doc); 
       alert(doc.body.innerHTML.substring(0, 50)); 
       } catch (e) { 
       // This can happen if the src of the iframe is 
       // on another domain TypeError:Cannot read property 'document' of undefined 
       alert('exception: ' + e); 
       } 
      }); 
    } 

}); 
+0

$( '身體')上( 'onload事件',框架,函數(){< - 。這似乎不可思議看起來像你試圖做一個在這種情況下,它會'加載'而不是'onload',你不能使用委託綁定。load事件不會冒泡。你需要綁定iframe本身。 – Taplar

+0

'frame'不會出現被追加到文檔中? – guest271314

回答

1

負載事件處理程序應該給我的iframe的內容,但 犯規發生。爲什麼?

frame變量不追加到document"onload"不是一個jQuery事件

$('body').on('onload',frame,function() {

不要求

$('<iframe />', { 
       name: 'frame1', 
       id: 'frame1'+index, 
       src: file_directory+"d"+data[index]     
      }).appendTo('body'); 

load事件。


嘗試調整js

var frame = $("<iframe />", { 
    name: "frame1", 
    id: "frame1" + index, 
    src: file_directory + "d" + data[index] 
}) 
// attach `load` event to `frame` before appending `frame` to `body` 
.on("load", function() { 
    // do stuff 
    console.log(1); 
    try { 
     // Displays the first 50 chars in the innerHTML of the 
     // body of the page that the iframe is showing. 
     // EDIT 2012-04-17: for wider support, fallback to contentWindow.document 
     var doc = frame.contentDocument || frame.contentWindow.document; 
     console.log(doc); 
     alert(doc.body.innerHTML.substring(0, 50)); 
    } catch (e) { 
     // This can happen if the src of the iframe is 
     // on another domain TypeError:Cannot read property "document" of undefined 
     alert("exception: " + e); 
    } 
}) 
// append `frame` to `body` after attaching `.on("load")` to `frame` 
.appendTo("body") 
+0

無法讀取'undefined'的屬性文檔。 – XWorm

+0

@XWorm _「無法讀取'undefined'的屬性文檔。」_在'try..catch'處是'alert'?在返回後是否有'js'問題描述的預期結果_「警報功能不起作用。」_? – guest271314

+0

其實,現在它工作正常。當文件存在時,它會下載它,當它沒有時會觸發異常錯誤。謝謝你的答案! – XWorm