如何在Jquery 3.3.1中制作AJAX表单

时间:2018-04-10 11:48:28

标签: jquery ajax

我将jQuery从1.10.2更新到3.3.1并且遇到了一些问题。当我填写输入并按下发送按钮时,我的网站只是重新加载,输入信息添加到我的网站的网址。它看起来像:

http://egorlero.com/2/?name=Jack&phone=%2B7+453+453-45-34&msg=Hello

控制台没有错误。

这是我的HTML代码:

$(btn).on("click", function() {
  if ($(this).hasClass('disabled')) {
    lightFill(); //show fill inputs
    lightEmpty(); //show empty inputs
    return false;
  } else {
    $(function() {
      var count = 0;
      $('#request_2').on("submit", function(e) {
        if (count == 0) {
          e.preventDefault();
          var data = $('#request_2').serialize();
          $.ajax({
            url: 'mail.php',
            type: 'POST',
            data: data,
          }).done(function(data) {

            //some code going here if success 

          }).fail(function() {

            //some code going here if error

          });
        }
        count++;
        return false;
      });
    });
  }
});
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/scripts_original.js"></script>

<div class="request">
  <form id="request_2">
    <input name="name" type="name" placeholder="Your name:" />
    <input name="phone" type="phone" placeholder="Your phone:" />
    <textarea name="msg" placeholder="Your message:"></textarea>
    <button id="submit" class="send_button disabled">Send</button>
  </form>
</div>

有人可以帮我解决这个问题吗?

尽管如此,请在我的网站底部免费测试此表单 - http://egorlero.com/index.html#anchor5

2 个答案:

答案 0 :(得分:0)

几个问题。令人惊讶的是,如果这曾经发挥作用。

我相信你想这样做。

  1. 使用表单提交活动
  2. 如果已提交,则停用该按钮
  3. 如果出现错误,可以启用该按钮,可能在.done而不是
  4. $("#request_2").on("submit", function(e) {
      e.preventDefault();
      var $theBut = $(this).find(".btn");
      if ($theBut).is('.disabled')) {
        $theBut.removeClass('disabled'); // enable the button?
        lightFill(); //show fill inputs
        lightEmpty(); //show empty inputs
        return false;
      }
      $theBut.addClass('disabled')  
      var data = $(this).serialize();
      $.ajax({
        url: 'mail.php',
        type: 'POST',
        data: data,
      }).done(function(data) {
        //some code going here if success 
      }).fail(function() {
         $theBut.removeClass('disabled')
      });
    });
    

答案 1 :(得分:-2)

您无需更改代码中的任何内容。只需将以下js添加到HTML页面:

<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>