如何使用 Ajax 将表单定位到 iframe?

How to target form to iframe with Ajax?

我还是 jQuery 的新手,所以我不能自己弄清楚所有事情。我有简单的 form 用于上传图片,jQuery 用于 progress bar 的插件,我根据 material 设计设计了样式,iFrame 用于上传文件。问题是,我无法将该表单定位到 iframe,它以某种方式停止了,我假设代码存在冲突。

这是HTML:

<form action="upload-sys.php" class="upload" enctype="multipart/form-data" method="post" target="galleryframe">
     <input class="chooseimg" id="fileToUpload" name="fileToUpload" type="file" /> 
     <input name="submit" type="submit" value="UPLOAD" />&nbsp;
</form>

<div class="progress">
    <div class="bar">
         &nbsp;</div>
</div>

<iframe name="galleryframe" onload="javascript:resizeIframe(this);" src="gallery-sys.php"></iframe>

jQuery:

<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
    var bar = $('.bar');
    $('form').ajaxForm({
        beforeSend: function() {
            var percentVal = '0%';
            bar.width(percentVal)
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal)
        }
    }); 
})();                   
</script>

我不明白为什么它不向 iframe 发送数据。然后我可以使用 php 重新加载 iframe 源并立即显示新图像。

我发现我可以通过添加这个来重定向整个页面(但显然这不是我需要的):

complete: function() {
    window.location.href = "url-of-target-page";
}

我也试过:

complete: function(responseText, statusText) {
     target.html(responseText);
     var target = 'galleryframe';
}

但运气不好。

谁能在这方面指导我?

complete: function(responseText, statusText) {
     target.html(responseText);
     var target = 'galleryframe';
}

你有两个问题:

  1. 您在尝试使用后给 target 一个值
  2. 该值是一个字符串,而不是 jQuery 对象,因此它没有 html 方法。

你需要更多类似的东西:

jQuery('iframe[name="galleryframe"]').
    contents().
    find('body').
    html(responseText);

我等不及了,所以我更加努力地尝试并找到了我需要的解决方案。我研究了 here 并编写了执行此操作的代码。这是:

$(document).ready(function() { 
    var options = { 
        beforeSend: nullWidth,
        uploadProgress: flexibleWidth,
        success: finalized,
    }; 
    $('#galleryform').ajaxForm(options); 
}); 

function nullWidth(options) { 
        var bar = $('.bar');
        var percentVal = '0%';
        bar.width(percentVal);
}
function flexibleWidth(event, position, total, percentComplete) { 
        var bar = $('.bar');
        var percentVal = percentComplete + '%';
        bar.width(percentVal);
}
function finalized(responseText, attr) {
        $('#uploadResult').contents().find('body').html(responseText);
        $('#galleryframe').attr("src", $('#galleryframe').attr("src"));
        var bar = $('.bar');
        var percentVal = '0%';
        bar.width(percentVal);
}