【问题标题】:Trouble with redirect after form submission表单提交后重定向问题
【发布时间】:2018-09-26 19:01:40
【问题描述】:

我有一个使用 jQuery 和 Ajax 来帮助管理多个文件上传的表单。一切正常,除了成功重定向。该脚本由堆栈用户 prateekkathal 提供,如下所示:

$(document).ready(function () //Setting up on Document to Ready Function
{
    $("#btnUpload").click(function (event) {

        //getting form into Jquery Wrapper Instance to enable JQuery Functions on form                    
        var form = $("#inquiry");

        //Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
        var params = form.serializeArray();

        //Getting Files Collection
        var files = $("#File1")[0].files;

        //Declaring new Form Data Instance  
        var formData = new FormData();

        //Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.  
        for (var i = 0; i < files.length; i++) {
            formData.append(files[i].name, files[i]);
        }
        //Now Looping the parameters for all form input fields and assigning them as Name Value pairs. 
        $(params).each(function (index, element) {
            formData.append(element.name, element.value);
        });

        //disabling Submit Button so that user cannot press Submit Multiple times
        var btn = $(this);
        btn.val("Uploading...");

        $.ajax({
            url: "relay2.php", //You can replace this with MVC/WebAPI/PHP/Java etc
            method: "post",
            data: formData,
            contentType: false,
            processData: false,
            success: function () {
                //Firing event if File Upload is completed!  
                alert("Upload Completed");
                btn.prop("disabled", false);
                btn.val("Submit");
                $("#File1").val("");
                window.location.replace('https://www.pmd-fla.com/thankyou2.html');
            },
        });
    });
});

我试图弄清楚如何在表单提交后将用户重定向到感谢页面。该脚本调用表单处理程序脚本,该脚本应该将用户重定向到感谢页面,但我认为success: function () 会妨碍您。我不确定如何编辑成功函数以将用户重定向到感谢页面。

任何指导将不胜感激。

编辑:我应该注意,当我在表单操作中包含表单处理程序的路径时,它会按预期工作,但会发送两次表单数据。我猜这是因为表单处理程序被调用了两次。一次来自 action 属性,一次来自上述脚本。

【问题讨论】:

  • 如果您想在表单提交后将用户发送到另一个页面,为什么要使用 AJAX 调用?那么为什么不直接使用常规的 html 表单提交呢?使用 AJAX 的目的是让它们保持在同一页面上。
  • @jwebb 该操作在 ajax 中有错误情况。如果他只是使用表单发布,当出现错误时用户将在错误的页面上
  • @Seth McClaine 错误也可以通过 HTML 表单发布来处理,而无需转到其他页面。
  • 说实话,我不知道我需要使用Ajax。这是我能找到的唯一一个似乎可以完成我想要做的事情的脚本。最终目标是允许用户通过单个输入字段上传多个文件,并将这些文件附加到提交时发送的电子邮件中。我的表单处理程序脚本不支持从单个输入上传多文件,因此我正在尝试找到解决方法。
  • 啊听起来你真正的问题是无法支持从单个输入上传多个文件

标签: jquery ajax forms


【解决方案1】:

你可以在你的成功函数中抛出window.location.href="{path}"。您会在收到警报后需要此信息,一旦单击警报,您就会被重定向 - 这可能会使您成功执行的其他所有操作都成为争议点

     $.ajax({
            url: "formHandler.php", //You can replace this with MVC/WebAPI/PHP/Java etc
            method: "post",
            data: formData,
            contentType: false,
            processData: false,
            success: function () {
               //Firing event if File Upload is completed!  
                alert("Upload Completed");
                /* you will redirect before the users have a chance to see these actions take effect unless you move them before the alert
                btn.prop("disabled", false); 
                btn.val("Submit");
                $("#File1").val("");
                */
                window.location.href = 'https://www.pmd-fla.com/thankyou2.html'; 
            },
            error: function (error) { alert("Error"); }
        });

您也可以尝试提交表单

假设表单是这样设置的......

<form id="inquiry" action="https://www.pmd-fla.com/thankyou2.html">


 $.ajax({
        url: "formHandler.php", //You can replace this with MVC/WebAPI/PHP/Java etc
        method: "post",
        data: formData,
        contentType: false,
        processData: false,
        success: function () {
           //Firing event if File Upload is completed!  
            alert("Upload Completed");
            /* you will redirect before the users have a chance to see these actions take effect unless you move them before the alert
            btn.prop("disabled", false); 
            btn.val("Submit");
            $("#File1").val("");
            */
            $('#inquiry').submit()
        },
        error: function (error) { alert("Error"); }
    });

【讨论】:

  • 麦克莱恩感谢您的回复。不幸的是,window.location 不起作用。它只是重新加载当前页面。也试过 window.location.href 和 window.location.replace 无济于事。
  • 您需要提供一个合格的路径,例如//stackoverflow.com 或完全合格的,例如https://stackoverflow.com
  • 我确实使用了这样的绝对 URL:window.location = '{pmd-fla.com/thankyou2.html}';。事实上,现在我什至没有收到包含表单数据的电子邮件。
  • window.location='https://www.pmd-fla.com/thankyou2.html'window.location='//www.pmd-fla.com/thankyou2.html'
  • 成功了!你真棒!将其发布为答案,以便我可以将其标记为“答案”。感谢您的时间和专业知识。
【解决方案2】:

您可以使用的另一种解决方案是通过 iframe 提交表单。这样用户仍会在同一页面上。

您需要添加 iframe:

<iframe name="ifrm_submit" id="ifrm_submit" style="display:none;"></iframe>

一旦有了这个 iframe,您就需要更改表单提交数据的方式。您可以通过将目标属性添加到表单元素来做到这一点。

<form target="ifrm_submit" method="post" action="formHandler.php">
    <!-- I assume that your multiple file inputs are part of this form -->
</form>

您还需要添加一个能够响应表单提交回调的 javascript 函数。

function fileUploaded(resp){
    if(resp.error == 0){
        window.location.href=resp.redirect_url;
    }else{
        alert(resp.message); //assuming there was an error and a message was set for the same
    }
}

在处理文件上传的 php 脚本中,您可以创建一些 json 数据,然后将其回显到 iframe 中。

<?php
//handle file upload, validation, etc.
$resp_data = [
    'error' => 0, //assuming there were no errors while uploading
    'redirect_url' => 'http://someurl.com'
    ];
echo '<script type="text/javascript"> window.parent.fileUploaded('.json_encode($resp_data).'); </script>';
die();
?>

这是它的工作原理:

  1. 表单通过 iframe 提交
  2. PHP 输出被发送到 iframe
  3. iframe 中的 javascript 代码被调用并调用父页面的 javascript 函数
  4. 父页面 javascript 处理收到的响应。

【讨论】:

  • 感谢您的回复。实际上,我按照 Seth McClain 的建议通过将感谢页面添加到表单的操作属性来解决它。
  • 为什么要避免使用 iframe:ostraining.com/blog/webdesign/against-using-iframes
  • 这只是我的朋友关于如何进行文件上传并仍然在同一页面上的建议。如果您使用 ajax,我完全同意成功处理程序的方法。我仍然不完全同意建议链接上的#1,因为 iframe 加载我的网站页面而不是任何第 3 方网站。 OP 确实提到他/她不确定是否需要 ajax。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2013-04-13
  • 1970-01-01
相关资源
最近更新 更多