如何在表单提交期间进行 $.get 调用

How to make $.get call during form submission?

本文关键字:get 调用 表单提交      更新时间:2023-09-26

我不想使用 AJAX 提交我的表单,但我想通过在表单提交期间向服务器发出几个 GET 请求来制作进度条,因为提交可能需要一段时间才能上传多个文件。我发现在webkit浏览器中,我无法在提交表单时发出GET请求,并且我看到将表单提交到iframe将允许我这样做。

标记如下所示:

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

而 JavaScript:

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

我仍然没有在 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
    });
  });
});

编辑

设置一个标志,该标志不允许表单提交,直到您收到响应表单您的 get 请求。收到回复后,设置标志以允许表单提交,然后以编程方式重新提交。

$(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();
       });
     }

  });
});

确定您的$.get请求已完成的唯一方法是确保表单不会提交并重定向页面,直到您的$.get请求完成。

编辑#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
        });
  });
});