0
我有發送POST請求到指定的RESTful服務,如果用戶名和密碼是正確的一個形式,它會返回翻譯和輸出AJAX對象請求
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>
任何幫助將是太棒了!
太謝謝你了! –
如果我想得到消息字符串,我將如何去輸出這個? –
@HarryBerry你可以通過'data.message'來訪問消息,但最終取決於你想顯示它的位置,如果你試圖將它寫入網頁,你需要操作DOM以顯示值該網頁,如果你只是想把它記錄到控制檯,你可以做'console.log(data.message)' – tt9