使用AJAX和PHP检查表单字段

时间:2016-05-14 13:58:01

标签: javascript ajax

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

  • 函数链接到表单
  • 的onsubmit
  • 向服务器发出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>

1 个答案:

答案 0 :(得分:0)

为每个字段链接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)"