Javascript 表单验证 + ajax 提交不起作用

标签 javascript jquery ajax forms validation

我正在使用 Javascript 来验证表单。如果验证脚本在表单中没有发现错误,那么 ajax 提交代码应该运行,但事实并非如此。我不知道为什么。如果我将提交代码放入其自己的脚本中并删除验证,则表单可以正常提交。我还应该注意,如果您在 $("#foo").submit(function(event) { 之前和之后放置 console.log("Success"),只能看到第一个控制台日志。因此看来提交函数由于某种原因没有触发。

<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou" onsubmit="return validateForm()">

  <div class="page1">
    <label class="row">
      <h2 class="headline">Your name</h2>
      <input placeholder="e.g. John Smith" type="text" name="name" id="name" tabindex="1" autofocus>
      <span id="nameError" class="error headline"></span>
    </label>

    <label class="row email">
      <h2 class="headline">Your email address</h2>
      <input placeholder="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a2bfa6aab7aba287b5a8a1a8b5a3a6b0a6b5a3e9a4a8e9b2ac" rel="noreferrer noopener nofollow">[email protected]</a>" type="text" name="email" id="email" tabindex="2">
      <span id="emailError" class="error headline"></span>
    </label>

    <label class="row">
      <h2 class="headline">Company name</h2>
      <input placeholder="e.g. Roford" type="text" name="company" id="company" tabindex="3">
      <span id="companyError" class="error headline"></span>
    </label>
    <div class="next">
      <button type="button" id="moveup">Next page</button><i class="icon-down-open"></i></div>
  </div>

  <div class="page2">
    <label class="row reason">
      <h2 class="headline">Reason for nomination</h2>
      <textarea id="textarea" rows="6" cols="25" maxlength="1000" name="message" id="message" placeholder="A brief evidence based summary"></textarea>
      <span id="messageError" class="error headline"></span>
      <div id="text-area-wrap">
        <div id="textarea_feedback"></div>
      </div>
    </label>

    <div class="row button-wrap">
      <div class="column small-12">
        <input class="button" name="submit" type="submit" id="contact-submit" value="Submit">
      </div>
    </div>
    <div class="prev">
      <button type="button" id="movedown">Previous page</button><i class="icon-up-open"></i></div>
  </div>

</form>


function validateForm() {
  var name = document.nomForm.name.value;
  var email = document.nomForm.email.value;
  var company = document.nomForm.company.value;
  var message = document.nomForm.message.value;
  var errorCount = 0;

  if (name == "") {
    document.getElementById('nameError').innerHTML = "Please enter your name";
    errorCount++;
  } else {
    var specCharNum = "~`!#$%^&*+=[]\\\';,/{}|\":<>?1234567890";
    for (var i = 0; i < name.length; i++) {
      if (specCharNum.indexOf(name.charAt(i)) != -1) {
        document.getElementById('nameError').innerHTML = "Please enter a valid name";
        errorCount++;
      }
    }
  }

  if (email == "") {
    document.getElementById('emailError').innerHTML = "Please enter your email address";
    errorCount++;
  } else {
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > email.length) {
      document.getElementById('emailError').innerHTML = "Please enter a valid email address";
      errorCount++;
    }
  }

  if (company == "") {
    document.getElementById('companyError').innerHTML = "Please enter a company name";
    errorCount++;
  } else {
    var specChar = "~`!#$%^&*+=[]\\\';,/{}|\":<>?";
    for (var i = 0; i < name.length; i++) {
      if (specChar.indexOf(name.charAt(i)) != -1) {
        document.getElementById('companyError').innerHTML = "Please enter a valid company name";
        errorCount++;
      }
    }
  }

  if (message == "") {
    document.getElementById('messageError').innerHTML = "Please enter a reason";
    errorCount++;
  } else {
    if (message.length > 1000) {
      document.getElementById('messageError').innerHTML = "You have exceeded the character limit";
      errorCount++;
    }
  }

  if (errorCount > 0) {
    return false;
  } else {
    // Variable to hold request
    var request;

    // Bind to the submit event of our form
    $("#foo").submit(function(event) {

      // Abort any pending request
      if (request) {
        request.abort();
      }
      // setup some local variables
      var $form = $(this);

      // Let's select and cache all the fields
      var $inputs = $form.find("input, select, button, textarea");

      // Serialize the data in the form
      var serializedData = $form.serialize();

      // Let's disable the inputs for the duration of the Ajax request.
      // Elements are disabled AFTER the form data has been serialized.
      // Disabled form elements will not be serialized.
      $inputs.prop("disabled", true);

      // Fire off the request to /form.php
      request = $.ajax({
        url: "https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
        type: "post",
        data: serializedData
      });

      // Callback handler that will be called on success
      request.done(function(response, textStatus, jqXHR) {
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
      });

      // Callback handler that will be called on failure
      request.fail(function(jqXHR, textStatus, errorThrown) {
        // Log the error to the console
        console.error(
          "The following error occurred: " +
          textStatus, errorThrown
        );
      });

      // Callback handler that will be called regardless
      // if the request failed or succeeded
      request.always(function() {
        // Reenable the inputs
        $inputs.prop("disabled", false);
      });

      // Prevent default posting of form
      event.preventDefault();
    });
    return true;
  }
}

最佳答案

首先从表单中删除 onsubmit 事件,如下所示:

<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou">

并使用以下 JavaScript 代码:

function validateForm() {
  var name = document.nomForm.name.value;
  var email = document.nomForm.email.value;
  var company = document.nomForm.company.value;
  var message = document.nomForm.message.value;
  var errorCount = 0;

  if (name == "") {
    document.getElementById('nameError').innerHTML = "Please enter your name";
    errorCount++;
  } else {
    var specCharNum = "~`!#$%^&*+=[]\\\';,/{}|\":<>?1234567890";
    for (var i = 0; i < name.length; i++) {
      if (specCharNum.indexOf(name.charAt(i)) != -1) {
        document.getElementById('nameError').innerHTML = "Please enter a valid name";
        errorCount++;
      }
    }
  }

  if (email == "") {
    document.getElementById('emailError').innerHTML = "Please enter your email address";
    errorCount++;
  } else {
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");

    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > email.length) {
      document.getElementById('emailError').innerHTML = "Please enter a valid email address";
      errorCount++;
    }
  }

  if (company == "") {
    document.getElementById('companyError').innerHTML = "Please enter a company name";
    errorCount++;
  } else {
    var specChar = "~`!#$%^&*+=[]\\\';,/{}|\":<>?";
    for (var i = 0; i < name.length; i++) {
      if (specChar.indexOf(name.charAt(i)) != -1) {
        document.getElementById('companyError').innerHTML = "Please enter a valid company name";
        errorCount++;
      }
    }
  }

  if (message == "") {
    document.getElementById('messageError').innerHTML = "Please enter a reason";
    errorCount++;
  } else {
    if (message.length > 1000) {
      document.getElementById('messageError').innerHTML = "You have exceeded the character limit";
      errorCount++;
    }
  }

  return errorCount;
}

$("#foo").submit(function(event) {

  var request;

  if ( validateForm() !== 0 ) {
    return false;
  }

  // Abort any pending request
  if (request) {
    request.abort();
  }
  // setup some local variables
  var $form = $(this);

  // Let's select and cache all the fields
  var $inputs = $form.find("input, select, button, textarea");

  // Serialize the data in the form
  var serializedData = $form.serialize();

  // Let's disable the inputs for the duration of the Ajax request.
  // Elements are disabled AFTER the form data has been serialized.
  // Disabled form elements will not be serialized.
  $inputs.prop("disabled", true);

  // Fire off the request to /form.php
  request = $.ajax({
    url: "https://script.google.com/macros/s/AKfycbwpTdztz-kSw8Ld1o0yly6BD-2cvJglpq2gkKioMjGoWDMO_HE/exec",
    type: "post",
    data: serializedData
  });

  // Callback handler that will be called on success
  request.done(function(response, textStatus, jqXHR) {
    // Log a message to the console
    console.log("Hooray, it worked!");
    console.log(response);
    console.log(textStatus);
    console.log(jqXHR);
    window.location = "nominate-test.html#thankyou";
  });

  // Callback handler that will be called on failure
  request.fail(function(jqXHR, textStatus, errorThrown) {
    // Log the error to the console
    console.error(
      "The following error occurred: " +
      textStatus, errorThrown
    );
  });

  // Callback handler that will be called regardless
  // if the request failed or succeeded
  request.always(function() {
    // Reenable the inputs
    $inputs.prop("disabled", false);
  });

  // Prevent default posting of form
  event.preventDefault();
});

它阻止重新加载页面,然后执行你的ajax代码。运行ajax后,使用javascript将用户重定向到感谢页面。

关于Javascript 表单验证 + ajax 提交不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44746994/

相关文章:

javascript - Firebase 函数 : How to store simple cookies to remember an authenticated user

javascript - 转换对象中的 JavaScript 点分字符串

javascript - jQuery 按钮集刷新无法按我的预期工作

javascript - 保存链接分配值以及转到其他页面

jquery - HTML5 全屏 API 退出按钮事件

jquery - 如何在 ASP.NET 中通过母版页使用 JCrop

angularjs - Python flask 和AngularJS与链接http post请求顺序

javascript - 将 Backbone Model 属性绑定(bind)到 TinyMCE 文本

javascript - 按 id 筛选数组 angularjs 的数组

javascript - 如何从异步调用返回响应?