【问题标题】:XMLHttpRequest does not fire for POST if both required fields are entered如果输入了两个必填字段,则不会为 POST 触发 XMLHttpRequest
【发布时间】:2020-05-23 12:44:35
【问题描述】:

您好,我正在尝试将用户 ID 和密码发送到 PHP 文件并在 json 中回显。如果当我只输入一个值时输入表单标签中有“必需”,它将返回带有该值的 json,而另一个作为空字符串返回。但如果我同时输入,它根本不会进入 XMLHttpRequest。 如果我删除“必需”,它也不能只输入一个值。谢谢!

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>first assignment</title>
    <link rel="stylesheet" href="style.css">
    <script>
      function curlcheck() {

        var user_id = document.getElementById("user_id").value;
        var pass = document.getElementById("password").value;

        var body = "ucid=" + user_id + "&password=" + pass;
        xhr = new XMLHttpRequest();
        xhr.open("POST", "front_curl.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function() {

          if (xhr.status === 200 && xhr.readyState === 4) {

            var response_json = JSON.parse(xhr.responseText);
            //checks for json and "success" value from it
            console.log("in successfull responce");
            console.log(response_json.success);
            console.log(response_json);



          } else {
            //checks when status did not come back successful 
            console.log("status NOT success");
            console.log(xhr.responseText);
          }
        };

        xhr.send(body);

      }

    </script>
  </head>

  <body>
    <div class="somebox"></div>
    <ul>
      <h3>Team 1 Online Exam System</h3>
    </ul>
    <form action="" method="POST">
      <div name="form header" class="formhead">
        <h1>Welcome</h1>
        <p><span id="loginerr" class="err_alert"></span></p>
      </div>
      <div class="login_box">
        <lable for="user_id">User ID</lable>
        <input type="text" placeholder="Enter User ID" id="user_id" required>

        <label for="password">Password</label>
        <input type="password" placeholder="Enter Password" id="password" required>

        <button id="but" type="submit" onclick="curlcheck()">Login</button>

      </div>
    </form>
    <div class="footer">
    </div>

  </body>

</html>

【问题讨论】:

    标签: javascript json forms xmlhttprequest


    【解决方案1】:

    如果你的required条件满足,你的表单默认发送不带js的post方式。

    否则您的表单不会发送,因为您没有填写必填字段,但这对 js 无关紧要,因此表单由 js(您的 xhr)发送

    您可以: 1)onclick="curlcheck(); return false"

    2) onclick="curlcheck" 并使 curlcheck 返回 false

    3) onclick="curlcheck", function curlcheck(event) { 并将event.preventDefault(); 放入函数中

    因此,您将阻止默认表单发送,只保留您的 xhr 工作

    【讨论】:

      猜你喜欢
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2012-04-17
      相关资源
      最近更新 更多