我在我的html模板中有这段代码。它会检查用户输入的学校名称,以及学校与我的数据库中关联的唯一ID。如何在代码执行前使JavaScript/Jquery/AJAX等待
$("#id_school").change(function() {
var school = $(this).val();
var identification_code = document.getElementById('id_identification_code')
if (identification_code != '' and school != '') {
$.ajax({
url: '/checks/validate_school/',
data: {
'school': school,
},
dataType: 'json',
success: function(data) {
console.log('Checked School')
if (data.code != identification_code) {
console.log(data.code);
document.getElementById('id_school').style.borderColor = 'red';
document.getElementById('id_identification_code').style.borderColor = 'red';
} else {
document.getElementById('id_school').style.borderColor = 'green';
document.getElementById('id_identification_code').style.borderColor = 'green';
}
}
});
}
});
正如你可以看到,如果在数据库中的代码和用户输入不匹配的代码,我想去红色的框。当他们这样做时,我希望它变绿。
问题是,只要我输入学校名称,在输入代码之前,两个框都会变红。我试图修复这与if(identification_code != '' and school != '')
但这没有奏效。
感谢您的帮助!
你错过了'VAL()''中选择id_identification_code'' – dloeda
如果{''首先是identification_code'一个DOM元素对象,所以永远不会等于''''。推测你的意思是'identification_code.value!='''。在JS中,'和'也是无效的语法。你需要'&&'而不是 –
@RoryMcCrossan我已经做了更改,但现在没有任何反应。轮廓不会改变颜色,也不会在控制台中记录任何内容。 – wtreston