0

我正在尝试访问并返回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 被加载,然后result在加载事件中返回变量。如何做到这一点?

4

1 回答 1

1

您不能从load回调中返回一个值,因为它是异步执行的,您可以做的是传递一个回调,该回调将在加载完成时调用。

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
})
于 2013-09-05T09:58:47.813 回答