jQuery AJAX 表单提交两次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20195483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:01:56  来源:igfitidea点击:

jQuery AJAX form submits twice

jqueryajaxsubmit

提问by James Privett

I've got a form that I'm capturing via jQuery and sending via AJAX. My problem is that the form submits more than once every time I refresh the page.

我有一个表单,我通过 jQuery 捕获并通过 AJAX 发送。我的问题是每次刷新页面时表单都会提交多次。

I've tried to unbind the submit button but then the form is posted normally after the first submit. Any help would be appreciated

我试图解除提交按钮的绑定,但是在第一次提交后表单会正常发布。任何帮助,将不胜感激

$('#exportForm').submit(function() {
  $.ajax({
    type: "POST",
    url: $(this).attr('action'),
    data: $(this).serialize(),
    success: function(response) {
      $('#exportForm').unbind('submit');
      console.log(response);
    }
  });
  return false;
});

采纳答案by DevlshOne

It's most likely that you're using a buttonor submitto trigger the ajax event. Try this:

您很可能正在使用buttonorsubmit来触发 ajax 事件。尝试这个:

$('#exportForm').submit(function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $(this).attr( 'action' ),
            data: $(this).serialize(),
            success: function( response ) {
                console.log( response );
            }
        });

        return false;
    });

回答by Chris Sercombe

As well as calling preventDefault, also call stopImmediatePropagation on the event.

除了调用 preventDefault 外,还对事件调用 stopImmediatePropagation。

$('#exportForm').submit(function(e){
    e.preventDefault();
    e.stopImmediatePropagation();
    $.ajax({
        type: "POST",
        url: $(this).attr( 'action' ),
        data: $(this).serialize(),
        success: function( response ) {
            console.log( response );
        }
    });

    return false;
});

回答by ddanurwenda

In case you are using some kind of validation (e.g jQuery Validation), the form is submitted twice because aside from $('#exportForm').submityou write yourself, the validation plugin will also submit the form after it successfully validates all field.

如果您使用某种验证(例如 jQuery 验证),表单将提交两次,因为除了$('#exportForm').submit您自己编写之外,验证插件还会在成功验证所有字段后提交表单。

NB : If you are using jQuery Validation, avoid using .submit(). Instead, use submitHandler.

注意:如果您使用 jQuery 验证,请避免使用.submit(). 相反,使用submitHandler.

回答by Gammer

You can simply use e.stopImmediatePropagation();:

您可以简单地使用e.stopImmediatePropagation();

For example :

例如 :

$('#exportForm').submit(function(e){
    e.stopImmediatePropagation();

回答by Vladimir Leonov

You should check your another js code, maybe somewhere it triggers twice "submit" event. This happened in my case, i forget "return false" in onclick handler for one button

你应该检查你的另一个 js 代码,也许它在某个地方触发了两次“提交”事件。这发生在我的情况下,我忘记了一个按钮的 onclick 处理程序中的“返回假”

回答by Adam

As Chris Sercombe pointed out, e.stopImmediatePropagation() does work and it definitely fixes the problem, but you shouldn't have to use it. The problem still exists in your code somewhere. Let me mention an example of how two post requests could be sent:

正如 Chris Sercombe 指出的那样, e.stopImmediatePropagation() 确实有效,它确实可以解决问题,但您不必使用它。问题仍然存在于您的代码中。让我举一个例子,说明如何发送两个 post 请求:

If you are using AngularJS, and lets say you make a controller called "HandleAjaxController" you could assign this ng-controller to a div, and then accidentally assign this same ng-controller to an inner div. This would cause the post request to be sent twice. So:

如果您使用的是 AngularJS,并且假设您制作了一个名为“HandleAjaxController”的控制器,您可以将这个 ng-controller 分配给一个 div,然后不小心将这个相同的 ng-controller 分配给一个内部 div。这将导致 post 请求被发送两次。所以:

    <div ng-controller='HandleAjaxController'>
        <div ng-controller='HandleAjaxController'>
            <button id="home" type="button" class="btn btn-success">Send data</button>

This caused a lot of stress for me one time because in my ng-route I had set the controller in here:

这有一次给我带来了很大的压力,因为在我的 ng-route 中,我在这里设置了控制器:

    $routeProvider
    .when("/", {
        templateUrl : "src/js/partials/home.html",
        controller : "HandleAjaxController"
    })

and then I set it again in my home.html: <div ng-controller='HandleAjaxController'>

然后我在 home.html 中再次设置: <div ng-controller='HandleAjaxController'>

Anyways, that is one example of how two posts could be sent.

无论如何,这是如何发送两个帖子的一个例子。

回答by Snziv Gupta

i have added jquery.unobtrusive-ajax.min.js ref twice as answered here https://stackoverflow.com/a/15041642/4412545

我已经添加了两次 jquery.unobtrusive-ajax.min.js ref 在这里回答https://stackoverflow.com/a/15041642/4412545

回答by gutkol

For someone who have almost same problem I can say that you should control your jQuery events away from function(){}, so the best to had only one request from ajax POST is to have events like this:

对于遇到几乎相同问题的人,我可以说你应该控制你的 jQuery 事件远离 function(){},所以最好只有一个来自 ajax POST 的请求是有这样的事件:

$(document).ready(function {
 $("#exportForm").click(function{
   $.ajax({
      type: "POST",
      url: "#", //your url
      data: data, //your variable
      success: function(){
        //do something here
      }
   });
 });
});

not in function which evokes second function like this:

不是在调用这样的第二个函数的函数中:

$(document).ready(function {
 exportingForm();

 function exportingForm(){
   $("#exportForm").click(function{
     $.ajax({
        type: "POST",
        url: "#", //your url
        data: data, //your variable
        success: function(){
          //do something here
        }
     });
   });
 }
});

回答by Eddie

Just want to point out, if you have more than one element with the same class, this can happen as well.

只是想指出,如果您有多个具有相同类的元素,这种情况也可能发生。

<button class="downvote">
  <img src="/img/thumbs-down.png" class="downvote">
</button>

回答by Kazario

The problem can be resolved by using a div in place of a button on your php form. A button is not needed due to the use of ajax.

该问题可以通过使用 div 代替 php 表单上的按钮来解决。由于使用了ajax,因此不需要按钮。