我正在尝试访问并返回在load事件中创建的result
变量:
function submit_form_with_file(form, link, file)
{
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" ></iframe>');
//append the iframe to the html page
$("body").append(iframe);
result="";
var form = $(form);
...
form.submit();
$(iframe).load(function ()
{
var body=window.frames[$(iframe).attr("name")].document.body;
result=(body.textContent || body.innerText);
alert(result);
});
return result;
}
当我执行return result
时,我想要两件事:等到我的iframe已加载,然后在load事件中返回result
变量。怎么实现呢?
答案 0 :(得分:1)
您不能从load
回调中返回avalue,因为它是异步执行的,您可以做的是传递一个回调,该回调将在加载完成时调用。
function submit_form_with_file(form, link, file, loadCallback) {
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
// append the iframe to the html page
$("body").append(iframe);
result = "";
var form = $(form);
// ...
form.submit();
$(iframe).load(function () {
var body = window.frames[$(iframe).attr("name")].document.body;
result = (body.textContent || body.innerText);
loadCallback(result);
});
return result;
}
然后
submit_form_with_file(form, link, file, function (result) {
//loading is completed, do something with result
})