JavaScript:检查远程服务器是否在线

时间:2017-04-17 16:21:48

标签: javascript cors jsonp jsfiddle remote-server

在将其标记为副本之前,请阅读。

我正在尝试使用javascript来模拟ping,例如它应该显示给定网站的状态(向上/向下)。

www.google.com =>截至
www.dummysite.com =>向下

我尝试了四种方法  1.使用AJAX(仅适用于同一源服务器)
 2.使用Image技巧(仅当远程服务器返回图像时才有效)
 3.使用JSONP(不作为服务器返回HTML页面)
 4.使用$ .getScript(适用于除lorem像素之外的所有网站,因为其MIME类型(' image / jpeg')不可执行。)我们不太明白它与3。

JSFiddle: CORS



Sub MergewithAutoFilter()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim rng As Range, SearchValue As String
    Dim StartDate As Date, EndDate As Date


Dim FilterField As Integer, RangeAddress As String
Dim ShName As Variant, RwCount As Long


'**************************************************************
'***Change these five lines of code before you run the macro***
'**************************************************************

' Change this to the path\folder location of the files.
MyPath = "C:\Users\ltigpec\Desktop\Search\"

' Fill in the name of the sheet containing the data.
' Use ShName = "Sheet Name" to use a sheet name instead if its
' index. This example uses the index of the first sheet in
' every workbook.
ShName = 1

' Fill in the filter range: A1 is the header of the first
' column and G is the last column in the range and will
' filter on all rows on the sheet.
' You can also use a fixed range such as A1:G2500.
RangeAddress = Range("A1:A" & Rows.Count).Address

' Set the field that you want to filter in the range
' "1 = column A" in this example because the filter range
' starts in column A.
FilterField = 1

' Fill in the filter value. Use the "<>" if you want to
' filter on the absence of a term. Or use wildcards such
' as "ron*" for cells that start with ron, or use
' "*ron*" if you look for cells where ron is a part of the
' cell value.
StartDate = Application.InputBox(Prompt:="Insert start date", Title:="DATE FIND", Default:=Format(Custom), Type:=1)
EndDate = Application.InputBox(Prompt:="Insert end date", Title:="DATE FIND", Default:=Format(Custom), Type:=1)
'SearchValue = Application.InputBox(Prompt:="Enter a Date to Locate on This Worksheet", Title:="DATE FIND", Default:=Format(Custom), Type:=1)


'**********************************************************
'**********************************************************


' Add a slash after MyPath if needed.
If Right(MyPath, 1) <> "\" Then
    MyPath = MyPath & "\"
End If

' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
    MsgBox "No files found"
    Exit Sub
End If

' Fill the myFiles array with the list of Excel files in the
' folder.
FNum = 0
Do While FilesInPath <> ""
    FNum = FNum + 1
    ReDim Preserve MyFiles(1 To FNum)
    MyFiles(FNum) = FilesInPath
    FilesInPath = Dir()
Loop

' Change application properties.
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
End With

' Add a new workbook with one sheet.
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1

' Loop through all files in the myFiles array.
If FNum > 0 Then
    For FNum = LBound(MyFiles) To UBound(MyFiles)
        Set mybook = Nothing
        On Error Resume Next
        Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
        On Error GoTo 0

        If Not mybook Is Nothing Then

            On Error Resume Next
            ' Set the filter range.
            With mybook.Worksheets(ShName)
                Set sourceRange = .Range(RangeAddress)
            End With

            If Err.Number > 0 Then
                Err.Clear
                Set sourceRange = Nothing
            End If
            On Error GoTo 0

            If Not sourceRange Is Nothing Then
                ' Find the last row in target worksheet.
                rnum = RDB_last(1, BaseWks.Cells) + 1

                With sourceRange.Parent
                    Set rng = Nothing

                    ' Remove the AutoFilter.
                    .AutoFilterMode = False

                    ' Filter the range on the
                    ' value in filter column.

                    sourceRange.AutoFilter Field:=FilterField, Criteria1:=">=" & StartDate & " *", Operator:=xlAnd, Criteria2:="<=" & EndDate & " *"


                    With .AutoFilter.Range

                        ' Check to see if there are results
                        ' after after applying the filter.
                        RwCount = .Columns(1).Cells. _
                                  SpecialCells(xlCellTypeVisible).Cells.Count - 1

                        If RwCount = 0 Then
                            ' There is no data, only the
                            ' header.
                        Else
                            ' Set a range without the
                            ' header row.
                            Set rng = .Resize(.Rows.Count - 1, .Columns.Count). _
                                      Offset(1, 0).SpecialCells(xlCellTypeVisible)


                            ' Copy the range and the file name
                            ' in column A.
                            If rnum + RwCount < BaseWks.Rows.Count Then
                                BaseWks.Cells(rnum, "A").Resize(RwCount).Value _
                                      = mybook.Name
                                rng.Copy BaseWks.Cells(rnum, "B")
                            End If
                        End If

                    End With

                    'Remove the AutoFilter
                    '.AutoFilterMode = False

                End With
            End If

            ' Close the workbook without saving.
           ' mybook.Close savechanges:=False
        End If

         'Open the next workbook.
   Next FNum

   ' Set the column width in the new workbook.
    BaseWks.Columns.AutoFit
    MsgBox "Look at the merge results in the new workbook " & _
       "after you click on OK."
End If

 'Restore the application properties.
With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = CalcMode
End With
End Sub
&#13;
var sites = {
  google: {
    url: "https://www.google.com",
    id: "googleStatus"
  },
  dummy: {
    url: "http://www.dummysitealphabeta2.com",
    id: "dummySiteStatus"
  },
  jsfiddle: {
    url: "https://fiddle.jshell.net",
    id: "jsfiddleStatus"
  },
  lorem: {
    url: "https://lorempixel.com/400/200/",
    id: "loremStatus"
  }
};

// Default
refreshAllSites('ajax');

function refreshAllSites(approach) {
  Object.keys(sites).forEach(function(name) {
    // Four approaches
    switch (approach) {
      case "ajax":
        // 1. Using AJAX (works only for the same origin)
        checkStatusUsingAJAX(sites[name]);
        break;

      case "image":
        // 2. Using Image trick (works only if 
        // the remote server returns image)
        checkStatusUsingImage(sites[name]);
        break;

      case "jsonp":
        // 3. Using JSONP (Doesn't work because server is an HTML page)
        checkStatusUsingJSONP(sites[name]);
        break;

      case "getscript":
        // 4. Using GetScript (Doesn't work for lorem pixel because its MIME type ('image/jpeg') is not executable.)
        checkStatusUsingGetScript(sites[name]);
        break;
    }
  });
}

// Approach 4: Using GetScript
function checkStatusUsingGetScript(site) {
  $.getScript(site.url + "?callback=?").done(function() {
    document.getElementById(site.id).innerHTML = "Up"
  }).fail(function() {
    document.getElementById(site.id).innerHTML = "Down"
  });
}

// Approach 3: Using JSONP
// Doesn't work as server returns an HTML page
function checkStatusUsingJSONP(site) {
  jsonp(site.url, function() {
    document.getElementById(site.id).innerHTML = "Up"
  }, function() {
    document.getElementById(site.id).innerHTML = "Down"
  });

  // Define JSONP
  function jsonp(url, success, fail) {
    var callbackName = 'jsonpCallback' +
      Math.round(10000 * Math.random());

    window[callbackName] = function(data) {
      console.log("calling callback");
      delete window[callbackName];
      document.body.removeChild(script);
      success(escape(data));
    }

    var script = document.createElement('script');
    script.src = url + "?callback=" + callbackName;
    script.onerror = fail;

    document.body.appendChild(script);
  }
}

// Approach 2: Using Image loading trick
// Only works if the remote server returns Image e.g. lorem pixel
// https://stackoverflow.com/a/5224638/351708
function checkStatusUsingImage(site) {
  var image = document.createElement("img");
  image.onload = function() {
    document.getElementById(site.id).innerHTML = "Up"
  };
  image.onerror = function() {
    document.getElementById(site.id).innerHTML = "Down"
  };

  image.src = site.url;
}


// Approach 1
// Using AJAX - It will only be successful in case of JSFiddle
// as for the rest of the sites it will throw CORS exception
function checkStatusUsingAJAX(site) {
  $.ajax(site.url).done(function() {
    document.getElementById(site.id).innerHTML = "Up"
  }).fail(function() {
    document.getElementById(site.id).innerHTML = "Down"
  });
};

// Other functions
var select = document.getElementById("approachOptions");
select.addEventListener("change", function(e) {
  refreshAllSites(this.value);
});
&#13;
table {
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border-bottom: 1px solid black;
}
&#13;
&#13;
&#13;

类似的问题:
Javascript: Check if server is online
Is it possible to ping a server from Javascript?
Use JSONP to load an html page
JavaScript XMLHttpRequest using JsonP

1 个答案:

答案 0 :(得分:0)

遇到同样的问题,构建了一个hacky解决方案:

http://ruthere.co/ https://github.com/glennzw/ruthere

示例:

var url = "https://stackoverflow.com";
var newImg = new Image;
newImg.src = "http://ruthere.co/u/" + url;
console.log("Checking " + url)

newImg.onload = function(){
    console.log(this.width);
    if (newImg.height == 200) {
        console.log("Stackoverflow is up!");
    } else {
        console.log("Stackoverflow broke :(");
    }
}