我有以下JS:
$('form').live('submit', function (event) {
// Stop the form from doing a native postback
event.preventDefault();
$.ajax({
type: 'POST',
timeout: 5000,
url: $(this).attr('action'),
data: $('form').serialize(),
success: function (responseHtml) {
$.getJSON($(this).attr('action'), function (data) {
console.log(data);
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('server error');
}
});
});
哪个应该从以下mvc方法中记录json失败(注意这是登录失败而不是ajax错误!):
[HttpPost]
public JsonResult Login(User user, string returnUrl)
{
// Validate the email and password
if (users.Login(user.UserName, user.Password, Request.UserHostAddress))
{
FormsAuthentication.SetAuthCookie(user.UserName, true);
// build redirectUrl ...
//var redirUrl = ...
return Json(new { uservalidated = true, url = false });
}
else
{
return Json (new { uservalidated = false, url = false });
}
}
如果我禁用JS然后我看到结果很好但由于某种原因JS无法看到它:/
答案 0 :(得分:1)
认为你必须在那里有JsonRequestBehavior.AllowGet
return Json(....., JsonRequestBehavior.AllowGet);
此外:
如果您使用Chrome,请在Firefox中按F12和Network,Firebug,看看是否有404,500或类似的错误,这些错误可能会解释为什么没有发生任何错误。
答案 1 :(得分:1)
$(this)
不是你在成功方法中所想的那样(因为它是一个回调而且用完了范围)。
您需要存储对this
的引用以创建闭包
$('form').live('submit', function (event) {
// Stop the form from doing a native postback
event.preventDefault();
var self = this; // add this so you have a reference to this in callbacks
$.ajax({
type: 'POST',
timeout: 5000,
url: $(this).attr('action'),
data: $('form').serialize(),
success: function (responseHtml) {
$.getJSON( $(self).attr('action') , function (data) {
console.log(data);
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('server error');
}
});
});