2012-11-17 48 views
1

我正在實現一個使用iframe的ajax圖片上傳功能。 我搜索過,發現了類似的問題,但我已經嘗試過,他們沒有爲我工作。 我的AJAX圖片上傳的工作原理如下:動態創建Iframe不可訪問

  • 用戶點擊「添加圖片」按鈕,動態創建一個新的對話框$('#imgdialog')。該對話框只是一個包含動態創建表單的div,其中包含$('#imgform')和一個iframe,$('#upload_target')
  • 該表格允許用戶通過ajax uplaod選擇一個文件,其中應該顯示在iframe中。

但是這不會發生。我正在學習本教程:http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

我的實現和教程中的主要區別在於,在我的實現中,表單和iframe不是在頁面加載時開始,它們是在當用戶點擊一個按鈕時飛行。

我知道我的PHP代碼工作正常,因爲當我使用FireBug時,我可以看到所需的POST和RESPONSE。但Iframe沒有被填充,儘管在FireBug中我可以看到它存在於HTML中,除了它是空的。

創建的動態表單和iframe的代碼是:

imgform = document.createElement('form'); 
    imgform.id = 'imgform'; 
    imgform.method='post'; 
    imgform.enctype='multipart/form-data'; 
    imgform.action ='upload_1.php'; 
    imgform.target = 'upload_target'; 
    imgform.onsubmit='showUploadedItem();'; 
    $('#imgform').append("Select image:<br /><input type='file' id='imgfile' />"); 
    $('#imgdialog').append("<iframe id='upload_target' name='upload_target' style='border:1px solid gray;' src='#'></iframe>"); 

    $('#upload_target').bind('load', function() { // doesn't work with .live either 
     $(this).contents().find("body").html('greetings from the iframe !'); 
     alert("loaded"); 
    }); 

$('#imgform')的,的onsubmit功能,我還包括以下行:

if($('#upload_target').length > 0){ alert("it's there"); } else {alert ("not there"); } 

而且我得到了「不存在」。

如何訪問iframe?

+0

使用.live代替.bind –

+0

我都試過,沒什麼區別調用它。 – user961627

+0

結帳我的答案,這是否解決了它? – Montagist

回答

0

問題是否有可能在iframe存在之前設置響應目標?我肯定已經把這些類型的事件綁定到iframe(我認爲即使是動態創建的)。儘管它有一些尷尬 - 可能需要jQuery中的一個非常小的插件,具體取決於你想要的加載事件類型。

另外,#imgdialog div在哪裏動態創建?不在此處的代碼中。也許你打算提供一個imgdialog的id。

0
$(document.body).on('DOMNodeInserted', 'iframe', function(e) { 
    console.log('inserted', e); 
}); 

var frame = document.createElement('iframe'); 
$(document.body).append(frame); 

或定義功能和iframe中的內容直接