[英]AJAX wrong password login response
我创建了一个简单的登录表单,该表单通过$.ajax
jQuery请求将数据发布到伪造的api 。
我有2个问题-
$("#my_form").submit(function (event) { event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); //get form action url var request_method = $(this).attr("method"); //get form GET/POST method var form_data = $(this).serialize(); //Encode form elements for submission $.ajax({ url: post_url, type: request_method, data: { username: "jordan", password: ["miguel"] }, }) .done(function (response) { $("#server-results").html(response); }); });
section class="form"> <h2>Login To Your Account</h2> <p class="valid">Valid. Please wait a moment.</p> <p class="error">Error. Please enter correct Username & password.</p> <form action="https://reqres.in/api/users" class="loginbox" method="post" id="my_login"> <input placeholder="Username" type="text" id="username"></input> <input placeholder="Password" type="password" id="password"></input> <button id="submit" value="Submit Form">Login</button> <div id="server-results"></div> </form> </section>
您应删除方括号,以确保成功登录,并根据文档按照以下格式进行操作
{
"email": "email@doamin.com",
"password": "password"
}
但是对于这些凭据,您需要先创建一个假用户
$.ajax({
url: "https://reqres.in/api/register",
type: "POST",
data: {
email: "email@domain.com",
password: "password"
},
success: function(response){
console.log(response);
}
});
成功注册后,它将返回您的令牌,如下所示,带有201 Response
{
"token": "QpwL5tke4Pnpja7X"
}
然后登录即可
$.ajax({
url: "https://reqres.in/api/login",
type: "POST",
data: {
email: "email@domain.com",
password: "password"
},
success: function(response){
console.log(response);
}
});
如果没有错误,则api将返回200 response
并带有以下json
{
"token": "QpwL5tke4Pnpja7X"
}
您可以签入您的成功函数以获取response.token
。
并检测登录尝试中是否有任何错误,API会使用以下json返回400 response
{
"error": "Missing password"
}
这样就意味着您可以使用error:function(response){}
显示错误希望对您有所帮助。
$.ajax({
url: post_url,
type: request_method,
data: {
email: "jordan@example.com", // replace username with email
password: "miguel" // remove the []
},
})
.done(function (response) { // status code 200
if(response.error) // handle wrong email or password ( login errors )
console.log(response.error);
else
$("#server-results").html(response);
})
.fail(function(err){ // to handle request errors ( 404, 400, 500 ... )
console.log(err);
});
并将https://reqres.in/api/login
放入您的form
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.