JavaScript - 如何为REST API请求创建可重用的函数?

时间:2017-06-25 16:56:15

标签: javascript html rest api frontend

我正在尝试为我的工作中的Web服务状态创建一些 UI仪表板,但我不知道如何重用我的代码,因为我可以重用我的请求一对主机并拆分响应以获取相关的“ led图标”。

理性的是点击一些HTML按钮并一次性发送一些 REST API 请求。 在响应中,我有一个IF语句来选择相关的LED图标并将其显示在HTML仪表板内的服务名称旁边。

enter image description here

我的代码运行正常,但IDK如何使其可重用。

var xhttp = new XMLHttpRequest();

  var ledTypes = {
    green: "<img src='green.png' height='30' width='30'>",
    red: "<img src='red.png' height='30' width='30'>",
    yellow: "<img src='yellow.png' height='30' width='30'>"
  };

function kongChecking() {
    //Kong - APIs services
    xhttp.open("GET", "http://blablabla.com:1111/bla1", false);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send();
    var response = JSON.parse(xhttp.responseText);
    console.log(xhttp.status);
}


function ledResponseK() {
    if (xhttp.status === 200 || 204) {
        document.write(ledTypes.green);
    }
    else if (xhttp.status === 500 || 404) {
        document.write(ledTypes.red);
    }
    else if (xhttp.status === 300 || 301 || 302) {
        document.write(ledTypes.yellow);
    }
};

一次性发送所有REST API请求的HTML元素 -

<a href="#tabs-2" onclick="kongChecking()" >Services status</a>

相关网络服务旁边的呈现回复图标 -

<script>ledResponse()</script><p align="center">Kong API's</p>

1 个答案:

答案 0 :(得分:1)

此功能的基本重用,仅针对此特定需求可以这样做 -

使用主机阵列调用公共函数,并使用相同的函数处理每个响应:

&#13;
&#13;
var hosts = ['https://www.url1.com', 'https://www.url2.com', 'https://www.url3.com']; //Added

var ledTypes = {
  green: "<img src='green.png' height='30' width='30'>",
  red: "<img src='red.png' height='30' width='30'>",
  yellow: "<img src='yellow.png' height='30' width='30'>"
};

function kongChecking() {

  var xhttp = new XMLHttpRequest();
  //Kong - APIs services
  for (var hostIndx = 0; hostIndx < hosts.length; hostIndx++) {
    try {
      xhttp.open("GET", hosts[hostIndx], false);
      xhttp.setRequestHeader("Content-type", "application/json");
      xhttp.send();
      var response = JSON.parse(xhttp.responseText);
      console.log(xhttp.status);
      //Handle response: (passing the current host first child - span element
      handleLedResponse(xhttp.status, hostIndx);
    } catch (err) {
      handleLedResponse(500, hostIndx);
    }
  }
}


function handleLedResponse(response, hostIndx) {
  var curSpan = document.getElementById('host_' + hostIndx);
  //Better switch this ugly nested if's to SWITCH / CASE
  if (response === 200 || 204) {
    curSpan.innerHTML = ledTypes.green;
  } else if (response === 500 || 404) {
    curSpan.innerHTML = ledTypes.red;
  } else if (response === 300 || 301 || 302) {
    curSpan.innerHTML = ledTypes.yellow;
  }
};
&#13;
div {
  width: 150px;
  display: inline-block;
}
&#13;
<a href="#tabs-1" onclick="kongChecking()">Check all status</a>
<br/>
<div>Host 1 Status <span id='host_0'></span></div>
<div>Host 2 Status <span id='host_1'></span></div>
<div>Host 3 Status <span id='host_2'></span></div>
&#13;
&#13;
&#13;