jquery - JSON响应太晚了
问题描述
我有这样的网址:
example.com/account/reset/6b183b5025d5b865963f4499f257705d
我的脚本中有一个 ajax 提交,如下所示:
form.ajaxSubmit({
url: '/account/reset',
success: function (result, status, xhr, $form) {
if (result.status === 'success') {
window.location.replace("/account/login");
}else{
btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
showErrorMsg(form, 'danger', result.message);
alert(result.status);
}
}
});
这是回应:
{"status":"success","title":"Success!","message":"Password changed successfully please login to continue"}
当表单 ajax 被提交时,我得到了一个响应,它触发了一个带有“未定义”的警报,在那个警报之后,我得到了成功状态的 json 响应。我怎么得到2个回应?以及如何在第一个响应之前捕捉到第二个响应?
如果需要,这是完整的 JS:
//== Class Definition
let reset = function () {
let reset = $('#m_login');
let showErrorMsg = function (form, type, msg) {
let alert = $('<div class="m-alert m-alert--outline alert alert-' + type + ' alert-dismissible" role="alert">\
<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>\
<span></span>\
</div>');
form.find('.alert').remove();
alert.prependTo(form);
//alert.animateClass('fadeIn animated');
mUtil.animateClass(alert[0], 'fadeIn animated');
alert.find('span').html(msg);
};
let resetPassword = function () {
$('#m_login_reset_submit').click(function (e) {
e.preventDefault();
let btn = $(this);
let form = $(this).closest('form');
form.validate({
rules: {
password: {
required: true,
minlength: 12
},
password_confirmation: {
required: true,
equalTo: '#password'
}
}
});
if (!form.valid()) {
return;
}
btn.addClass('m-loader m-loader--right m-loader--light').attr('disabled', true);
form.ajaxSubmit({
url: '/account/reset',
success: function (result, status, xhr, $form) {
if (result.status === 'success') {
window.location.replace("/account/login");
}else{
btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
showErrorMsg(form, 'danger', result.message);
alert(result.status);
}
}
});
});
};
//== Public Functions
return {
// public functions
init: function () {
resetPassword();
}
};
}();
//== Class Initialization
jQuery(document).ready(function () {
reset.init();
$(document).ajaxError(function (e, xhr, opt, thrownError) {
swal({
title: xhr.status + " " + xhr.statusText,
//text: "Error requesting : " + opt.url +" "+ thrownError,
text: xhr.responseText,
type: "error",
timer: 15000
});
$('#m_login_signin_submit').removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
});
});
解决方案
我不知道您为什么会看到两个警报窗口,或者即使是这样,因为您对它的描述有点模棱两可。但是,您得到的原因undefined
是 JavaScript 不会自动解码 JSON 数据。因此,您需要先将 JSON 解码为数据结构:
success: function (encoded, status, xhr, $form) {
decoded = JSON.parse(encoded)
if (decoded.status === 'success') {