我对网络技术很陌生,这让我发现大部分技术都很困难。我想要实现的是,当提交表单时,应该首先检查互联网连接,然后再进行Ajax调用。
我尝试这样使用navigator.onLine:
if(navigator.onLine == true) {
//code comes here
} else {
alert('Internet connection is lost');
$('#error').append("No internet connection. We could not submit the form");
}
有人可以告诉我如何修改我的代码以满足我的需要。
$('document').ready(function(){
/* validation */
$("#licence-form").validate({
rules:
{
licence: {
required: true
},
},
messages:
{
licence:{
required: "License key is required"
},
},
submitHandler: licenceForm
});
/* validation */
/* submit */
function licenceForm()
{
var data = $("#licence-form").serialize();
$.ajax({
type : 'POST',
url : '../includes/b0a012.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('Validating...');
},
success : function(response)
{
if(response=="yes"){
$(".hideit").hide();
$(".shows").show();
setTimeout(' window.location.href = "../setup.php"; ',4000);
}else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger text-center"> <img src="../images/attention.png" width="45" height="40" /> <br/> '+response+'</div>');
});
}
}
});
return false;
}
});
最佳答案
navigator.onLine 属性对于此目的并不真正可靠。实现differ并且状态仅在实际连接尝试时更新。
相反,将 error
处理程序添加到 $.ajax
参数对象:
error: function(xhr, status, error) {
$(".hideit").hide();
$(".shows").show();
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger text-center"> <img src="../images/attention.png" width="45" height="40" /> <br/> '+status+' ' + error + '</div>');
});
}
关于jquery - 提交表单之前检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205146/