【问题标题】:Include jQuery function in HTML form在 HTML 表单中包含 jQuery 函数
【发布时间】:2019-03-17 10:34:44
【问题描述】:

我想将我的 jQuery 函数调用到 HTML 标记中。我的登录表单连接到 Azure 数据库,我希望在客户端按下登录按钮时出现带有特定消息的模式弹出窗口(如果用户是数据库)。

在我的 jQuery 脚本中,如果连接为真,我想通过将我重定向到另一个页面来处理该错误,如果不是,则更改弹出窗口中的消息。

现在,它没有进入 jQuery 函数,我一直只得到真正的消息,即使它是假的。

jQuery 脚本:

<script>
  function checkForm(e) {
    e.preventDefault();
    $.post("https://studentshiftregister.azurewebsites.net/api/Login", function (data, status) {
      if (status === "200") {
        window.location.href = "#Portfolio";
        return true;
      } else {
        //display error information in the current form page
        $("#postLoginMessage").html("<font color=red>Login unsuccessfull!</font>");
        return false;
      }
    });
  }
</script>

HTML 表单:

<form action="https://studentshiftregister.azurewebsites.net/api/Login" method="post" role="form" class="contactForm" onsubmit="checkForm()">
  <div class="form-group">
      <input type="email" class="form-control input-text" name="email" id="email" placeholder="Email" data-rule="email" data-msg="Please enter a valid email" />
      <div class="validation"></div>
  </div>
  <div class="form-group">
    <input type="password" name="password" class="form-control input-text" id="password" placeholder="Password" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
    <div class="validation"></div>
  </div>

  <div class="text-center"><button id="myBtn" type="submit" class="input-btn" >Login</button></div>
</form>
<div id="myModal" class="modal" >

  <!-- Modal content -->
  <div class="modal-content" > 
    <span class="close">&times;</span>
    <p id="postLoginMessage">Welcome back!</p>
  </div>

</div>

【问题讨论】:

  • 您确定 API 正常工作吗?因为它返回 404
  • 你的回答是真实的吗?你得到 status: true 作为响应。
  • $.post是异步的,没有使用回调函数的返回值。
  • API 正在工作,我只是在这个例子中改变了它,它返回 200 为真,401 为假

标签: javascript jquery html forms function


【解决方案1】:

您正在调用checkForm(),但没有参数,但该函数希望第一个参数是Event 对象,因此它可以调用e.preventDefault()。改变

onsubmit="checkForm()"

到:

onsubmit="checkForm(event)"

【讨论】:

  • 它仍然无法正常工作,当它为假时仍然返回欢迎。我是 jQuery 新手,不知道要改什么
  • 当用户不存在时只是 401 Unauthorized。
  • console.log(typeof status, status) 显示什么?
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 2011-04-16
  • 2012-08-07
相关资源
最近更新 更多