简体   繁体   English

提交表单时如何拨打$ .get?

[英]How to make $.get call during form submission?

I don't want to submit my form with AJAX, but I want to make a progress bar by making a couple of GET requests to the server during form submission, since the submission might take a while with multiple file uploads. 我不想使用AJAX提交表单,但是我想通过在表单提交过程中向服务器发送几个GET请求来创建进度栏,因为提交可能需要一段时间才能上传多个文件。 I've found that in webkit browsers, I can't make GET requests while the form is submitting and I was seeing that submitting the form to an iframe would allow me to do it. 我发现在Webkit浏览器中,在提交表单时我无法发出GET请求,而且我发现将表单提交到iframe可以使我做到这一点。

The markup looks like this: 标记如下所示:

<form action="/my-action" target="target-iframe">
...
</form>
<iframe name="target-iframe"></iframe>

And the JavaScript: 和JavaScript:

$(document).ready(function() {
  $("form").on("submit", function() {
    $.get("/other-action", function(data) {
      // Use data returned here
    });
  });
});

I'm still not getting data back on the GET request--how can I get this to work? 我仍然无法从GET请求中获取数据-如何使它正常工作?

$(document).ready(function() {
  $("form").on("submit", function(e) { //add a parameter e - the event object
     e.preventDefault(); //stop the form from submitting
    $.get("/other-action", function(data) {
      // Use data returned here
    });
  });
});

EDIT 编辑

Set a flag that won't allow the form to submit until you've received your response form your get request. 设置一个标记,该标记将在您收到get请求的响应表之前不允许提交该表。 Once you've received your response, set your flag to allow your form to submit and then resubmit it programmatically. 收到回复后,将标志设置为允许表单提交,然后以编程方式重新提交。

$(document).ready(function() {
  var canISubmit = false;
  $("form").on("submit", function(e) { //add a parameter e - the event object
     var el = $(this);
     if(!canISubmit) {
       e.preventDefault();


       $.get("/other-action", function(data) {
         canISubmit = true;
         el.submit();
       });
     }


  });
});

The only way to be certain that your $.get request was completed is to make sure that the form doesn't submit and redirect the page until your $.get request completes. 只有这样,可以肯定,你的$.get请求完成是确保形式不提交和重定向的页面,直到你的$.get请求完成。

EDIT #2 编辑#2

$(document).ready(function() {

  $("form").on("submit", function(e) { //add a parameter e - the event object
     e.preventDefault();

     $.post("url",$(this).serialize())
        .done(function(response,status,jqXHR) {

            $.get("/other-action")
                .done(function(response,status,jqXHR) {
                    //other stuff done

                    //refresh the page or do whatever....
                })
                .fail(function() {
                    //$.get failed
                });

        })
        .fail(function() {
            //$.post failed
        });

  });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM