HTML/JQuery:按钮在根本不应该提交的时候提交一次

HTML/JQuery: Button submits once when it shouldn't at all

本文关键字:提交 JQuery 候提交 一次 按钮 HTML 不应该      更新时间:2023-09-26

我正在使用jQuery来允许表单提交,所以我不希望表单自行提交。

这是我的表格:

<form class="navbar-form navbar-right" id="signform">
   <div class="form-group">
      <input type="text" placeholder="Username" class="form-control">
    </div>
    <div class="form-group">
      <input type="password" placeholder="Password" class="form-control">
    </div>
    <button id="signbtn" class="btn btn-success">Sign in</button>
</form>

这是我的JQuery代码:

var signingIn = false;
$(document).ready(function() {
    $('#signbtn').click(function() {
        if (signingIn) return;
        signingIn = true;
        var img = $('<img id="loader" style="padding-left: 10px;" src="loader.gif"/>');
        $(this).after(img);
        var data = $('signform').serialize();
        $.ajax({
            url: '/logs',
            type: 'post',
            data: data,
            done: function() {
                $('#loader').remove();
                alert('success');
            }
        });
    });
});

现在,当我转到 url: website.com/index.html 并单击登录时,它会刷新页面(我根本不想要的内容)并转到 website.com/index.html? - 现在当我再次单击它时,什么也没发生(正是我一直想要的,所以我通过 jQuery 添加的元素不会丢失)。

你想像这样使用 jQuery ajax 调用:

$(document).on('click','button#signbtn', function(){
        var $form = $('form#signform');
        var url = $form.attr('action');
        $.ajax({
               type: "POST",
               enctype: 'mutipart/form-data',
               url: url,
               data: $form.serialize(), // serializes the form's elements.
               success: function(data){// whatever you want your code to do on success}
             })
        return false; // avoid to execute the actual submit of the form.
    });
$(function() {
  $( '#signform' ).submit(function(e) {
    e.preventDefault();
     $.ajax({
       type: 'POST',
       url: $(this).attr( 'action' ),
       data: $(this).serialize(),
       success: function(result) {
         // Do something on success
       }
     });
  });
});