首页 > 解决方案 > 使用 jQuery AJAX 验证登录表单

问题描述

在下面的代码中alert是给我的undefined。我认为问题是由于 URL 中的反斜杠或其他原因造成的。这是json结构

"{
            \"UserName\":\"abc\",
            \"Password\":\"123456\"
}"

如何验证用户输入的用户名和密码是否存在于 URL 中?

<form action="#" id="loginForm">
  <div class="form-group">
    <label for="userName" class="font-weight-bold" style="width:100%;">Username<a href="#" class="float-right font-weight-light axa-color">Forgot?</a></label>
    <input type="text" class="form-control" id="userName" name="userName" placeholder="Enter Email">
  </div>
  <div class="form-group">
    <label for="password" class="font-weight-bold" style="width:100%;">Password<a href="#" class="float-right font-weight-light axa-color">Forgot?</a></label>
    <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password">
  </div>
  <button type="button" id="login_btn" class="btn btn-lg btn-block">LOGIN</button>
</form>
$("#login_btn").click(function() {
  var userName = $("#userName").val();
  var password = $("#password").val();
  authenticate(userName, password);
});

function authenticate(userName, password1) {
  $.ajax({
    type: "POST"
    url: "http://api/User/login",
    dataType: 'json',
    async: false,
    data: {
      username: userName,
      password: password1
    },
    success: function(data) {
      alert(data);
    }
  })
};

标签: jqueryajax

解决方案


您在传递给$.ajax函数的对象中有错字,您需要,after "POST"

$("#login_btn").click(function() {
  var userName = $("#userName").val();
  var password = $("#password").val();
  authenticate(userName, password);
});

function authenticate(userName, password1) {
  $.ajax({
    type: "POST",
    url: "https://reqres.in/api/users",
    dataType: 'json',
    async: false,
    data: {
      username: userName,
      password: password1
    },
    success: function(data) {
      console.log(data);
    }
  });
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" id="loginForm">
  <div class="form-group">
    <label for="userName" class="font-weight-bold" style="width:100%;">Username<a href="#" class="float-right font-weight-light axa-color">Forgot?</a></label>
    <input type="text" class="form-control" id="userName" name="userName" placeholder="Enter Email">
  </div>
  <div class="form-group">
    <label for="password" class="font-weight-bold" style="width:100%;">Password<a href="#" class="float-right font-weight-light axa-color">Forgot?</a></label>
    <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password">
  </div>
  <button type="button" id="login_btn" class="btn btn-lg btn-block">LOGIN</button>
</form>


推荐阅读