Problem: XMLHttpRequest - handle server connection lost

自闭症网瘾萝莉.ら 提交于 2019-12-21 14:12:39

问题


How do I handle the scenario where I making a synchronous request to the server using XMLHttpRequest and the server is not available?

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"


回答1:


Ok I resolved it by using try...catch around xmlhttprequest.send

:

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



回答2:


Try the timeout property.

xmlHTTP.TimeOut= 2000 



回答3:


You don't check for properly returned status. By the code you gave you are doing a GET request. 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.

You can find a detailed explanation here :Ajax Tutorial by Mozilla

  
xmlhttp.onreadystatechange=function()

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





来源:https://stackoverflow.com/questions/377231/problem-xmlhttprequest-handle-server-connection-lost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!