简体   繁体   English

问题:XMLHttpRequest-处理服务器连接丢失

[英]Problem: XMLHttpRequest - handle server connection lost

How do I handle the scenario where I making a synchronous request to the server using XMLHttpRequest and the server is not available? 如何处理使用XMLHttpRequest向服务器发出同步请求而服务器不可用的情况?

xmlhttp.open("POST","Page.aspx",false);
xmlhttp.send(null);

Right now this scenario results into a JavaScript error: "The system cannot locate the resource specified" 现在,此方案导致JavaScript错误:“系统无法找到指定的资源”

Ok I resolved it by using try...catch around xmlhttprequest.send 好吧,我通过使用try ... catch xmlhttprequest.send解决了它

:

xmlhttp.open("POST","Page.aspx",false);              
       try
       {
       xmlhttp.send(null);
       }
       catch(e)
       {
            alert('there was a problem communicating with the server');
       }       

尝试超时属性。

xmlHTTP.TimeOut= 2000 

You don't check for properly returned status. 您不检查返回的状态是否正确。 By the code you gave you are doing a GET request. 根据您提供的代码,您正在执行GET请求。 To properly check the status of your request, you must create an event handler for the onreadystatechange event and then inside it check if the readyState property is equal 4 and then inside the method if the status is 200. 为了正确检查请求的状态,必须为onreadystatechange事件创建一个事件处理程序,然后在其中检查readyState属性是否等于4,然后在方法内部检查状态是否为200。

You can find a detailed explanation here : Ajax Tutorial by Mozilla 您可以在此处找到详细的说明: Mozilla的Ajax教程

 
xmlhttp.onreadystatechange=function()

xmlhttp.open("GET","Page.aspx",false);
{
  if (xmlhttp.readyState==4) 
  {
     if (xmlhttp.status==200)
     {
       //Ajax handling logic
     }
  }
}
xmlhttp.send(null);



声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM