问题描述
我有一个网站,其后端位于不同的主机上。我正在使用 XHRHttpRequest
提交表单数据。但是,有时我的提供商不可用,或者托管服务器上正在进行一些技术工作。并且在提交表单时,用户不会收到任何通知,因为服务器没有响应。控制台包含以下文本:net::ERR_NAME_NOT_RESOLVED
。所以问题是,如果再次发生这种情况,我该如何向用户显示错误?如何使用 JS 检测此错误?
const form = document.getElementById('contact_form');
form.addEventListener('submit',function(e) {
e.preventDefault();
const send = {
name: document.querySelector('input[name=name]').value,email: document.querySelector('input[name=email]').value,subject: document.querySelector('input[name=subject]').value,message: document.querySelector('input[name=message]').value
};
const jsonString = JSON.stringify(send);
const xhr = new XMLHttpRequest();
const action = form.getAttribute('action');
xhr.open('POST',action,true);
xhr.setRequestHeader('Content-type','text/plain');
xhr.onload = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xhr.responseText);
};
xhr.send(jsonString);
});
我尝试这样做:
if (this.readyState == 0) {
alert('The server is temporarily unavailable,please try again later!');
}
和
if (this.status == 503) {
alert('The server is temporarily unavailable,please try again later!');
}
但是还是不行。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)