1

我正在实现一个使用 iframe 的 ajax 图片上传功能。我搜索了 SO 并发现了类似的问题,但我已经尝试过了,但它们对我没有用。我的 ajax 图片上传工作如下:

  • 用户点击“添加图片”按钮,动态创建一个新的对话框$('#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')'s, onSubmit 函数中,我还包括以下行:

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

我得到了“不在那里”。

如何访问 iframe?

4

2 回答 2

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

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

或定义函数并直接从 iframe 内容中调用它

于 2012-11-17T10:35:13.433 回答
0

问题是否可能是您在 iframe 存在之前设置响应目标?我已经将这些事件的侦听器绑定到 iframe(我认为甚至是动态创建的)。不过它有些尴尬——可能需要一个非常小的 jQuery 插件,这取决于你想要什么样的加载事件。

另外,动态创建的#imgdialog div 在哪里?不在此处的代码中。也许您打算改为提供 imgdialog 的 id。

于 2012-11-17T10:14:53.950 回答