我有一个表单,如果用户名和密码正确,它将向指定的 RESTful 服务发送 POST 请求,它将返回
Object {status: "success", message: "Welcome!"}
如果有错误,它将返回
Object {status: "error", message: "Incorrect username or password."}
两者都在控制台中通过
console.log(data)
有没有办法我可以获取这些对象并访问它们并为每个响应做一些事情,例如显示一个元素等。
请在下面找到我的代码。
$(document).ready(function() {
$("#login-form").submit(function(e) {
e.preventDefault();
var formData = {
'username': $('#username').val(),
'password': $('#password').val(),
};
$.ajax({
type: 'POST',
url: 'URL HERE',
data: formData,
success: function(data) {
// Here's where you handle a successful response.
console.log();
},
error: function() {
$('#error').show().text("There seems to be a problem logging in.");
}
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
<form name="login-form" id="login-form" method="post" action="URL HERE">
<label id="error">Sorry it seems your credentials are incorrect</label>
<div class="inputBlock">
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</div>
<div class="inputBlock">
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</div>
<input type="submit" value="Login" id="submit" />
</form>
任何帮助都会太棒了!
您可以使用 Javascript 检查返回对象的属性
//In your done function just treat "data" like an object
.done(function(data) {
if(data.status === "success"){
//Do something
}
else if (data.status === "error"){
//Display error
}
});