提交表单而不打开新的 window 或标签

Submitting form without opening new window or tab

所以我尝试使用 Ajax 提交表单,以防止它在提交时打开一个新标签(这在创建多张图片时非常烦人,因为会生成一个新标签每张图片)

这将提交表单并正常运行,但它会打开一个新选项卡。

// Submits form
$("#image-base-edit").submit();

但是我尝试了 @abc123 suggestion on this post 并修改了他的代码,使其看起来像下面的代码片段,但是通过这种方式提交,图像并没有真正创建。

/* attach a submit handler to the form */
$("#image-base-edit").submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get some values from elements on the page: */
    var $form = $(this),
        term1 = $form.find('input[name="id"]').val(),
        term2 = $form.find('input[name="title"]').val(),
        term3 = $form.find('input[name="image_file"]').val(),
        url = $form.attr('action');

    /* Send the data using post */
    var posting = $.post(url, {
        name: term1,
        title: term2,
        image_file: term3
    });

    /* Prints Done */
    posting.done(function(data) {
        console.log("done");
    });
});

// Submits form
$("#image-base-edit").submit();

这是 HTML 表格:

<!--Image Create FORM-->
<form name="edit_form" method="post" enctype="multipart/form-data" class="enableUnloadProtection enableAutoFocus enableFormTabbing enableUnlockProtection d-none" action="" id="image-base-edit" target="_blank">
    <fieldset id="fieldset-default" class="formPanel" style="display: block;">
        <legend id="fieldsetlegend-default" style="visibility: hidden; font-size: 0px; padding: 0px; height: 0px; width: 0px; line-height: 0;">Default</legend>
        <input name="id" value="image.2018-05-10.9629264509" originalvalue="image.2018-05-10.9629264509" type="hidden">
        <div class="field ArchetypesStringWidget  kssattr-atfieldname-title" data-fieldname="title" data-uid="0fd3d162687e4bd8917bc9830d616043" id="archetypes-fieldname-title">
            <input name="title" class="blurrable firstToFocus" id="title" value="" size="30" maxlength="255" placeholder="" type="text">
        </div>
        <div class="field ArchetypesImageWidget  kssattr-atfieldname-image" data-fieldname="image" data-uid="0fd3d162687e4bd8917bc9830d616043" id="archetypes-fieldname-image">
            <div id="appendInputhere">
            </div>
        </div>
    </fieldset>
    <div class="formControls">
        <input name="form.submitted" value="1" originalvalue="1" type="hidden">
        <input class="context" name="form.button.save" value="Save" type="submit">
    </div>
</form>

添加到 "appendInputhere" 中的内容如下所示。

<input size="30" name="image_file" id="image_file" type="file">

如果有更简单的方法来做到这一点,我可能会忽略,请告诉我。基本上我希望表单的功能与当前完全相同,除了打开新选项卡或在用户中加载新页面 window,我希望用户不必看到更改。

因此,在阅读更多内容并尝试找到一种方法来执行我上面写的原始方法时,我了解到可以将表单的目标设置为 iframe。所以为了解决我上面的问题,创建了这个 iframe...

<iframe name="formSubmitFrame" name="formSubmitFrame" tile="Holds Submitted form data" rel="nofollow" class="d-none"></iframe>

并将其设置为不在任何地方显示。然后,我将 iframe 的目标设置为 "formSubmitFrame"。

这最终实现了我在提交表单时用户看不到任何 window 或选项卡更改的目标。