我有一个表单,如果用户名和密码正确则返回指定的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>
任何帮助都会很棒!
答案 0 :(得分:2)
您可以使用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
}
});