简体   繁体   English

使用jQuery,IFRAME从(模拟的)异步文件上传中读取响应

[英]Reading response from (simulated) asynchronous file upload with jQuery, IFRAME

I am simulating an asynchronous file upload by targeting an iframe, like so: 我通过以iframe为目标来模拟异步文件上传,如下所示:

<form id="upload_form" action="upload.php" method="POST" enctype="multipart/form-data" target="upload_iframe">
  <input type="file" name="upload_input" />
  <iframe id="upload_iframe" name="upload_iframe" src=""></iframe>
</form>

After a file is selected, the form is submitted like so (using jQuery): 选择一个文件后,就这样提交表单(使用jQuery):

$('#upload_input').change(function() {
  $('#upload_form').submit();
});

The file is uploaded, and the JSON response is sent to the iframe. 文件已上传,并且JSON响应发送到iframe。 In Firebug, I can see that the iframe's content is: 在Firebug中,我可以看到iframe的内容是:

<html>
<head></head>
<body>{"success":true}</body>
</html>

I am using the iframe's load event to wait for the response. 我正在使用iframe的load事件来等待响应。 The load event is firing. 加载事件正在触发。 (It actually fires twice, which is a minor issue.) However, I can't figure out how to read the response. (它实际上会触发两次,这是一个小问题。)但是,我不知道如何读取响应。 I have tried various calls, but none of them return anything: 我尝试了各种呼叫,但是没有一个返回任何东西:

$('#upload_iframe').find('body')
$('#upload_iframe').html()
$('#upload_iframe').text()

Is there something I am missing? 我有什么想念的吗?

这应该做你的工作$('#upload_iframe')。find('body')。text()

I have found a solution that works, although it seems less than ideal. 我发现了一个可行的解决方案,尽管它似乎并不理想。 This code goes in the iframe load event handler: 这段代码在iframe加载事件处理程序中:

if (!$(this)[0].contentDocument.childNodes[0].children[1].childNodes[0]) 
{
  return;
}
var response = $(this)[0].contentDocument.childNodes[0].children[1].childNodes[0].wholeText;
var json = $.parseJSON(response);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM