使用AJAX和PHP检查表单字段

Checking form fields with AJAX and PHP

本文关键字:检查表 表单 字段 检查 PHP AJAX 使用      更新时间:2023-09-26

我正在尝试编写一个代码,如果用户名/邮件已经注册,该代码将检入php文件。以下代码不起作用,因为在check_fields()中,当为两个文件激发check_field()时,会立即发送返回,而无需等待异步查询完成。我不想使用JQuery,所以我想做以下事情:

  • 函数链接到表单的取消提交
  • 对服务器进行AJAX调用以启动php文件
  • 该文件分析输入并在需要时返回错误响应:"字段为空"、"电子邮件已使用"、"错误的电子邮件地址"等
  • AJAX调用完成后,将触发一个函数(或回调)。此函数将检查<span id="username_err"></><span id="mail_err"></>的.textContent,以查看php是否注意到错误。如果它不是空的(输入中有问题),函数会向初始函数返回false
  • 返回值被发送回表单
  • 如果为true,则表单将提交到服务器

这就是我想尝试的,可以吗?有没有办法在没有承诺的情况下做到这一点?

[原始代码]

<html>
        <body>
          <form style="text-align:center" action="mama.php" method="post" onsubmit="return check()">
            <div class="username">
              <span id="label_username">Username :</span>
              <input type="text" id="username" name="username">
              <p id="username_err"></p>
            </div><br />
            <div class="mail">
              <span id="label_mail">Mail :</span>
              <input type="text" id="mail" name="mail"></input>
              <p id="mail_err"></p>
            </div><br />
            <input type="submit" id="envoyer" value="Envoyer" />
          </form>
        </body>
        <script>
          function check() {
            return check_fields(['username', 'mail']);
          }
          function check_fields(items) {
            var check = true;
            for (i = 0; i < items.length; i++) {
              check_field(items[i]);
            };
            for (i = 0; i < items.length; i++) {
              var value = document.getElementById(items[i] + '_err').textContent;
              if (value != '') {
                check = false
              }
            };
            return check
          }
          function check_field(id) {
            var value = document.getElementById(id).value;
            ajax_php(id, value, 'check_field.php', function(returned_value) {
              document.getElementById(id + '_err').innerHTML = returned_value;
            });
          }
          function ajax_php(id, value, file, fn) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
              if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                fn(xmlhttp.responseText);
              }
            };
            xmlhttp.open('GET', file + '?' + id + '=' + value, true);
            xmlhttp.send();
          }
        </script>
        </html>

[可能的解决方案]

<html>
<body>
  <form style="text-align:center" action="mama.php" method="post" onsubmit="check(this)">
    <div class="username">
      <span id="label_username">Username :</span>
      <input type="text" id="username" name="username">
      <p id="username_err"></p>
    </div><br />
    <div class="mail">
      <span id="label_mail">Mail :</span>
      <input type="text" id="mail" name="mail"></input>
      <p id="mail_err"></p>
    </div><br />
    <input type="submit" id="envoyer" value="Envoyer" />
  </form>
</body>
<script>
  function check_fields(form, items) {
    var success = true;
    function check_field(i) {
      var id = items[i];
      var value = document.getElementById(id).value;
      ajax_php(id, value, 'check_field.php', function(returned_value) {
        document.getElmentById(id + '_err').textContent = returned_value;
        if (returned_value != '') {
          success = false;
        }
        if (++i < items.length) {
          check_field(i); // Check the next field
        } else if (success) { // reached the last field with no errors
          form.submit();
        }
      });
    }
    check_field(0);
  }
  function check(form) {
    check_fields(form, ['username', 'mail']);
    return false; // prevent form submission
  }
  function ajax_php(id, value, file, fn) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        fn(xmlhttp.responseText);
      };
    };
    xmlhttp.open('GET', file + '?' + id + '=' + value, true);
    xmlhttp.send();
  };
</script>
</html>

为每个字段链接AJAX调用。字段i的回调将提交AJAX调用以检查字段i+1,依此类推。如果全部成功,则最后一次回调将提交表单。

function check_fields(form, items) {
    var success = true;
    function check_field(i) {
        var id = items[i];
        var value = document.getElementById(id).value;
        ajax_php(id, value, 'check_field.php', function(returned_value) {
            document.getElementById(id + '_err').textContent = returned_value;
            if (returned_value != '') {
                success = false;
            }
            if (++i < items.length) {
                check_field(i); // Check the next field
            } else if (success) { // reached the last field with no errors
                form.submit();
            }
        });
    }
    check_field(0);
}
function check(form) {
    check_fields(form, ['username', 'mail']);
    return false; // prevent form submission
}

表格应包含:

onsubmit="return check(this)"