Javascript 以HTTP错误消息为目标

Javascript 以HTTP错误消息为目标,javascript,ajax,http,Javascript,Ajax,Http,我正在尝试使用AJAX将JSON编码的数据字符串发送到远程机器。 每当我尝试将数据字符串发送到远程计算机时,都会出现以下两条错误消息之一: XMLHttpRequest cannot load http://10.1.0.139:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allo

我正在尝试使用AJAX将JSON编码的数据字符串发送到远程机器。 每当我尝试将数据字符串发送到远程计算机时,都会出现以下两条错误消息之一:

XMLHttpRequest cannot load http://10.1.0.139:8000/. 
No 'Access-Control-Allow-Origin' header is present on 
the requested resource. Origin 'http://localhost' is 
therefore not allowed access.
当远程计算机通电并接受连接时,会出现此消息。然而,尽管我收到了这个错误,但我的代码完全按照我所希望的那样工作——就像远程机器接收到正确的数据一样

POST http://10.1.0.139:8000/ net::ERR_CONNECTION_REFUSED
当远程机器关闭电源或没有运行自己的服务器来接受传入的请求和连接时,就会出现此消息

问题是,我希望能够区分这两条错误消息,但我不知道如何区分。我不能使用诸如error()或fail()之类的AJAX回调,因为总会有一个错误——它会说,尽管HTTP状态为200,但请求失败,这表明一切正常(当第一条错误消息显示时)

有没有一种方法可以让我执行类似于“如果我无法连接到远程机器,请执行…”的伪命令的操作 编辑

我刚才注意到,我的远程计算机不显示来自Internet Explorer的传入连接,而是显示以下内容:


使用XMLHttpRequest超时

var xhr = new window.XMLHttpRequest();
var data = 'x=1';
xhr.open('POST', 'http://10.1.0.139:8000/');
xhr.timeout = 5000;
xhr.addEventListener('timeout', function(e) {
   // handle dead server 
   console.log('timeout');
   console.error(e);
});
xhr.addEventListener('error', function(e) {
   // handle error - CORS probably in this case
   console.log('error');
   console.error(e);
});
xhr.addEventListener('load', function(e) {
   // handle success
   console.log('load');
   console.info(e);
});
xhr.send(data);

这会在CORS错误的情况下触发
error
,在没有服务器的情况下触发
timeout

在8000处向服务器添加CORS响应。。。然后,您将能够读取服务器在:8000发送的任何响应。或者,XMLHttpRequest确实有一个
timeout
设置和一个
timeout
事件……我认为超时方法不起作用,因为通常在几秒钟内它会报告说“net::ERR\u CONNECTION\u denied”真的吗?哪个浏览器(以及它的哪个版本)会这样做?谷歌Chrome 54.0.2840.99版,是的,唯一被触发的是
错误
奇怪-我似乎记得这与广告拦截器或类似的东西有关?仔细阅读,它一定是真的
var xhr = new window.XMLHttpRequest();
var data = 'x=1';
xhr.open('POST', 'http://10.1.0.139:8000/');
xhr.timeout = 5000;
xhr.addEventListener('timeout', function(e) {
   // handle dead server 
   console.log('timeout');
   console.error(e);
});
xhr.addEventListener('error', function(e) {
   // handle error - CORS probably in this case
   console.log('error');
   console.error(e);
});
xhr.addEventListener('load', function(e) {
   // handle success
   console.log('load');
   console.info(e);
});
xhr.send(data);