3 回答

TA貢獻1851條經驗 獲得超5個贊
看看這個 jquery 教程。我個人會使用 Fail 和 Done 回調方法。修改您的 c# 控制器以返回不同的 HTTP 狀態代碼。當他們傳遞一個好的用戶名和密碼時使用 HTTP 200。當他們傳遞錯誤的密碼時使用 HTTP 400 這應該會觸發 Fail() 回調并允許您警告失敗。
https://learn.jquery.com/ajax/jquery-ajax-methods/
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "post.php",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
$( "<h1>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\">").html( json.html ).appendTo( "body" );
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown )** {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
});

TA貢獻1911條經驗 獲得超7個贊
這就是我最終存檔如何返回無效密碼錯誤消息的方式,也許它可以在當天幫助某人:)
我創建了一個enum來保存 MessageType 的值:
public enum MessageType
{
Valid,
InvalidEmail,
InvalidUerNameAndPass,
}
然后我更改我的控制器以獲得不同的 MessageType:
public JsonResult Login(string Mail, string pass)
{
MessageType messageType = MessageType.InvalidEmail;
using (DbNamesapce db = new DbNamesapce())
{
var query = // do Join
select new
{
//Select Something
};
var user = query.FirstOrDefault();
if (user == null)
{
return Json(new { messageType = MessageType.InvalidEmail }, JsonRequestBehavior.AllowGet);
}
if (user != null && CheckPass)
{
messageType = MessageType.Valid;
}
else
{
messageType = MessageType.InvalidUerNameAndPass;
}
return Json(new { messageType = messageType }, JsonRequestBehavior.AllowGet);
}
}
我將腳本更改為:
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '@Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (response) {
switch ($.trim(response.messageType))
{
case '@Convert.ToInt32(YourNAmeSpace.Models.MessageType.Valid)':
alert("Valid");
break;
case '@Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidEmail)':
alert("InvalidUerNameAndPass");
break;
case '@Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidUerNameAndPass)':
alert("InvalidUerNameAndPass");
break;
}
}
});
});
});
</script>

TA貢獻1859條經驗 獲得超6個贊
正常的做法是將響應狀態設置為 401 并省略通常的數據負載,該數據負載將與成功響應一起發送。然后由客戶端代碼來識別錯誤狀態并做出適當的響應(例如,可能通過顯示警報并保留在名稱/密碼表單上);此客戶端行為將在$.ajax
調用中指定。
- 3 回答
- 0 關注
- 293 瀏覽
添加回答
舉報