首页 > 解决方案 > 在不打开新窗口或标签的情况下提交表单

问题描述

所以我试图使用 Ajax 提交一个表单,以防止它在提交时打开一个新选项卡(这在创建多个图像时会变得非常烦人,因为每个图像都会生成一个新选项卡)

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

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

然而,我在这篇文章中尝试了@abc123 的建议,我修改了他的代码,使其看起来像下面的代码片段,但是通过这种方式提交,图像实际上并没有被创建。

/* 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">

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

标签: javascriptjqueryajaxformsplone-4.x

解决方案


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

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

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

这最终实现了我提交表单的目标,而用户不会看到任何窗口或选项卡的变化。


推荐阅读