JavaScript checks whether a server can be connected
This article describes how to find available addresses from multiple server servlets in js.
After a project is deployed in a production environment, there will be a production network segment (that is, you can access it at home) and an office network segment (which can only be accessed at the company ).
After our project is deployed, the external system calls our servlet. At this time, we need to check which address to connect to, that is, the address to be connected in js.
The specific js Code is as follows:
Function getXhr () {var httpreq = null; // ActiveXObjectif (window. activeXObject) {try {httpreq = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {try {httpreq = new ActiveXObject ("Microsoft. XMLHTTP ");} catch (e) {}} else if (window. XMLHttpRequest) {httpreq = new XMLHttpRequest ();} return httpreq;} function checkIsConnect (url) {var xmlhttp = getXhr (); xmlhttp. open ("GET", url, false); try { Xmlhttp. send (null);} catch (e) {return false;} if (xmlhttp. readyState = 4) {// readyStatud = 4 indicates interaction with the server, that is, return true;} return false;} function test () {var urls = new Array ("http: // zhw: 7001/CommonWeb/", "http: // 127.4.0.1: 7001/finance/", "http: // zhw: 7031/CommonWeb/"); var checkUrl = null; for (var I = 0; I <urls. length; I ++) {if (checkIsConnect (urls [I] + "testServlet") {checkUrl = urls [I]; break ;}} If (checkUrl! = Null) {// logic processing after obtaining the available server address} else {alert ("IP detection of unconnected network services, please check the network connection or confirm the server configuration! Server Configuration address: "+ urls );}}