暂停表单提交以进行验证

发布于 2024-10-02 13:41:24 字数 5248 浏览 3 评论 0原文

我有一些表单,可以在 iframe 中上传文件。我想保留它的提交,直到我检查它是否对 ajax 有效。我该怎么做?我的代码暂停提交并返回验证结果(当前只是一个返回“结果”:“true”的虚拟函数),但随后不执行“提交”操作。另外,在获得响应 200 状态后需要大约 2 秒才能显示响应数据,这是否正常?

这是我的 html:

<div id="message" style="background:black; width:400px; height:80px; display:none; color:white;">
</div>
<h1>Submit</h1>
<form action="{{upload_url}}" target="upload_target" method="POST" id="file_upload_form" enctype="multipart/form-data">
    {% render_upload_data upload_data %}
    <table>{{ form }}</table>    
    <p>
        <input type="hidden" maxlength="64" name="myfileid" value="{{ myfileid }}" >
    </p>
    <p>
        <input type="submit" id="file_upload_submit" value="Submit" />
    </p>
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>

Js:

$(function() {

    $('#file_upload_submit').click(function(e){
        e.preventDefault();
        var fileUploadForm = document.getElementById('file_upload_form');

        $.ajax({
            type: "POST",
            url: '/artifact/upload/check-form/',
            data: 'foo=bar',
            dataType: "json",
            success: function(data){
                if(data['result'] == "true"){
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span>'+data["message"]+'</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);
                     $('#file_upload_form').attr('target','upload_target').submit(function(){
                        alert('Handler for .submit() called.');
                        return false;
                    });
                }
                else{
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span">'+data["message"]+'</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);                    
                    return false;
                }
            }
        });
        return false;        
    });

});    

</script>

和链接: http://ntt.vipserv.org/artifact/


编辑

使用下面的代码我能够执行验证,然后当结果为肯定时提交表单。现在,如果我对表单的目标进行硬编码,则不会显示我的警报,并且我非常确定上传不会执行(不幸的是,上传列表每 8 小时刷新一次,我会知道它是否在某个时间起作用)。如果未指定目标,文件将通过重定向上传,因此整个“提交”事件侦听器将被忽略。

<script>  
    $('#fake_upload_submit').click(function(e){
        e.preventDefault();

        var fileUploadForm = document.getElementById('file_upload_form');
        fileUploadForm.addEventListener("submit", function() {
            alert("sent in iframe");
            fileUploadForm.target = 'upload_target';
        }, false);       

        $.ajax({
            type: "POST",
            url: '/artifact/upload/check-form/',
            data: 'foo=bar',
            dataType: "json",
            success: function(data){
                if(data['result'] == "true"){
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span>'+data["message"]+'</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);

                    fileUploadForm.submit();

                }
                else{
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span">Response false</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);                    
                    return false;
                }
            }
        });
        return false;        
    });   
</script>

html:

<div id="message" style="background:black; width:400px; height:80px; display:none; color:white;">
</div>
<h1>Submit</h1>
<form action="{{upload_url}}" method="POST" target="" id="file_upload_form" enctype="multipart/form-data">
    {% render_upload_data upload_data %}
    <table>{{ form }}</table>    
    <p>
        <input type="hidden" maxlength="64" name="myfileid" value="{{ myfileid }}" >
    </p>
    <p>
        <input type="submit" style="display:none" id="true_upload_submit" value="Submit" />
    </p>    
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
    <p>
        <input type="submit" id="fake_upload_submit" value="Submit" />
    </p>

I have some form, which uploads file in an iframe. I'd like to hold it's submission until I'll check if it's valid with ajax. How can I do this ? My code pauses the submission and returns validation result (currently just a dummy function which returns 'result': 'true') but then the 'submit' action is not performed. Also Is it normal that it takes ~2s to show response data after getting response 200 status ?

Here's my html:

<div id="message" style="background:black; width:400px; height:80px; display:none; color:white;">
</div>
<h1>Submit</h1>
<form action="{{upload_url}}" target="upload_target" method="POST" id="file_upload_form" enctype="multipart/form-data">
    {% render_upload_data upload_data %}
    <table>{{ form }}</table>    
    <p>
        <input type="hidden" maxlength="64" name="myfileid" value="{{ myfileid }}" >
    </p>
    <p>
        <input type="submit" id="file_upload_submit" value="Submit" />
    </p>
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>

Js:

$(function() {

    $('#file_upload_submit').click(function(e){
        e.preventDefault();
        var fileUploadForm = document.getElementById('file_upload_form');

        $.ajax({
            type: "POST",
            url: '/artifact/upload/check-form/',
            data: 'foo=bar',
            dataType: "json",
            success: function(data){
                if(data['result'] == "true"){
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span>'+data["message"]+'</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);
                     $('#file_upload_form').attr('target','upload_target').submit(function(){
                        alert('Handler for .submit() called.');
                        return false;
                    });
                }
                else{
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span">'+data["message"]+'</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);                    
                    return false;
                }
            }
        });
        return false;        
    });

});    

</script>

and link:
http://ntt.vipserv.org/artifact/


EDIT

With the code below I'm able to perform validation, then when it's result is positive form is submitted. Now if I hardcode target for form, my alert is not shown and I'm pretty sure that the upload is not performed (unfortunately list of uploads is refreshed each 8h sa I'll know if it worked in some time). If target is not specified, file is uploaded with redirect so the whole 'submit' event listener is ommitted.

<script>  
    $('#fake_upload_submit').click(function(e){
        e.preventDefault();

        var fileUploadForm = document.getElementById('file_upload_form');
        fileUploadForm.addEventListener("submit", function() {
            alert("sent in iframe");
            fileUploadForm.target = 'upload_target';
        }, false);       

        $.ajax({
            type: "POST",
            url: '/artifact/upload/check-form/',
            data: 'foo=bar',
            dataType: "json",
            success: function(data){
                if(data['result'] == "true"){
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span>'+data["message"]+'</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);

                    fileUploadForm.submit();

                }
                else{
                    $("#message").show();
                    $("#message").fadeIn(400).html('<span">Response false</span>');
                    setTimeout(function(){
                        $("#message").fadeOut("slow", function () {
                            $("#message").hide();
                        });
                    }, 1500);                    
                    return false;
                }
            }
        });
        return false;        
    });   
</script>

html:

<div id="message" style="background:black; width:400px; height:80px; display:none; color:white;">
</div>
<h1>Submit</h1>
<form action="{{upload_url}}" method="POST" target="" id="file_upload_form" enctype="multipart/form-data">
    {% render_upload_data upload_data %}
    <table>{{ form }}</table>    
    <p>
        <input type="hidden" maxlength="64" name="myfileid" value="{{ myfileid }}" >
    </p>
    <p>
        <input type="submit" style="display:none" id="true_upload_submit" value="Submit" />
    </p>    
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
    <p>
        <input type="submit" id="fake_upload_submit" value="Submit" />
    </p>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

蓝海似她心 2024-10-09 13:41:24

验证后,您注册了一个新的提交事件处理程序,但没有任何内容提交表单,因此您必须再次单击该按钮才能提交表单。

您可以只提交表单,而不添加提交处理程序:

$('#file_upload_form').attr('target','upload_target').submit();

After the validation you register a new submit event handler, but there is nothing that submits the form, so you would have to click the button again to get it submitted.

You can just submit the form instead of adding a submit handler:

$('#file_upload_form').attr('target','upload_target').submit();
金兰素衣 2024-10-09 13:41:24

我认为您可能对表格的提交考虑过多,但我也可能读错了。我也可能没有掌握所有事实。通过ajax调用提交表单并返回提交结果(验证失败或成功)不是更好吗?

伪代码:

jQuery:

var formData = data;
ajax(formData);

表单处理:

if(valid) {
  submit(formData);
  return true;
} else {
  return false;
}

如果需要,我可以提供真实的代码。

I'm thinking that you might be over thinking the submission of the form, but I might also be reading this wrong. I may also not have all of the facts. Would it not be better to just submit the form via the ajax call and return the result of the submission (validation failed or succeeded)?

Pseudo code:

jQuery:

var formData = data;
ajax(formData);

Form Processing:

if(valid) {
  submit(formData);
  return true;
} else {
  return false;
}

I can provide real code if needed.

孤独陪着我 2024-10-09 13:41:24

如果您使用同步 XHR 而不是异步,这对您来说可能是最简单的(如果可能对您的用户来说更烦人)。

或者,使用 JavaScript 拦截表单提交,并在服务器端验证成功时使用 XHR 提交。

It would likely be easiest for you (if possibly more annoying for your users) if you used synchronous XHR instead of asynchronous.

Alternatively, intercept the form submission using JavaScript and submit it using XHR iff the server-side validation succeeds.

彩虹直至黑白 2024-10-09 13:41:24

如何完全避免这个问题,有一个隐藏的提交按钮来提交表单,并有一个可见的按钮来开始验证,如果可以,那么它会执行单击正确的隐藏提交按钮?

How about avoiding the problem altogether, having a hidden submit button to submit the form and have a visible button that starts validation and if it's ok then it performs a click on the proper hidden submit button ?

清风疏影 2024-10-09 13:41:24

古法是正确的。我相信以下更改将使第一个脚本起作用。更改

                     $('#file_upload_form').attr('target','upload_target').submit(function(){
                        alert('Handler for .submit() called.');
                        return false;
                    });

                     $('#file_upload_form').attr('target','upload_target').submit();

“是您的调试破坏了提交”。如果您想继续调试,请将代码更改为:

                     $('#file_upload_form').attr('target','upload_target').submit(function(){
                        alert('Handler for .submit() called.');
                        return true;
                    }).submit();

您必须单独调用submit()来触发提交事件。如果提交函数返回 false,它将不会继续,因此您必须让它返回 true

这是您发布的该问题的第三个版本。我同意其他人的观点,即您可能以过于复杂的方式解决问题。在这种情况下,您可能希望完全避免 JavaScript 并转而使用简单的 HTML 帖子。是否有令人信服的理由表明这不是一个选择?

Guffa is correct. I believe the following change will make the first script work. Change

                     $('#file_upload_form').attr('target','upload_target').submit(function(){
                        alert('Handler for .submit() called.');
                        return false;
                    });

to

                     $('#file_upload_form').attr('target','upload_target').submit();

It's your debugging that has broken the submission. If you want to keep the debugging, change the code to:

                     $('#file_upload_form').attr('target','upload_target').submit(function(){
                        alert('Handler for .submit() called.');
                        return true;
                    }).submit();

You must call submit() on its own to trigger the submission event. If the submit function returns false, it will not continue, so you must have it return true instead.

This is the third version of this question that you've posted. I agree with others that you may be addressing your problem in a way that is overcomplicated. This is a case where you may want to avoid JavaScript altogether and go for a straightforward HTML post. Is there a compelling reason why this is not an option?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文