我正在发送AJAX POST请求以获取登录表单。如果我输入了错误的组合或正确的组合,那么ajax会发送该请求以及所有其他请求
错误登录:
function incorrect() {
$('#loginModal .modal-dialog').addClass('shake');
$('.error').addClass('alert alert-danger').html("Username ou password incorretos!");
$('input[type="password"]').val('');
setTimeout(function () {
$('#loginModal .modal-dialog').removeClass('shake');
}, 1000);
}
正确登录:
function correct() {
$('#loginModal .modal-dialog');
$('.error').removeClass('alert alert-danger');
$('.error').addClass('alert alert-success').html("Logado com sucesso!");
$("#reglogin").toggle();
$("#conta").toggle();
}
Ajax调用:
function loginAjax() {
$("form").on("submit", function (x) {
x.preventDefault();
var form = $(this);
$.ajax({
type: 'POST',
url: '/Login/Login',
traditional: true,
data: form.serialize(),
success: function (data) {
if (data === false) {
incorrect();
} else if (data === true) {
correct();
}
}
});
});
}
控制器:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ToString());
SqlCommand cmd = new SqlCommand();
public ActionResult Login(string username, string password)
{
conn.Open();
string passstr = Encrypt(password);
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandText = string.Format("select * from Cliente where Username='{0}' and Password='{1}'", username, passstr);
reader = cmd.ExecuteReader();
if (reader.Read())
{
Session["Username"] = username;
string valueFromSession = Session["Username"].ToString();
conn.Close();
return Json(data: true);
} else
{
conn.Close();
return Json(data: false);
}
}
每次提交表格时,我只希望发送一个请求
谢谢!
答案 0 :(得分:1)
我将$("form").on("submit", function (x)
更改为$("form").off("submit").on("submit", function (x)
,并且有效