如何呈现对HTML的JSONP GET响应

时间:2017-07-01 11:56:28

标签: javascript jquery ajax rest get

我尝试向多个主机发送GET请求,并在每个主机的分离敌人中呈现响应状态。 它下面的代码适用于xhttp请求但是在 jsonp 数据类型的情况下(为了避免Access-Control-Allow-Headers错误)我需要使用另一个json类型发送请求,不能使用常规功能。 在下面的代码中使用ajax请求,我没有设法使用responseHandler函数来呈现响应状态。 请帮助您解决此代码的问题。

var hosts = ['http://www.bla.com:8082/bla','http://www.bla2.com:8082/bla','http://www.bla3.com:8082/bla', 'http://www.bla4.com:8082/bla']; //Added


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

var hostIndx = 0;

function collectionChecking() {

    for  (hostIndx < hosts.length; hostIndx++;) {
           $.ajax({
                url: hosts[hostIndx],
                dataType: "jsonp",
                jsonpCallback: "_stdout",
                cache: false,
                crossDomain: true,
                timeout: 10000,
               success: handleLedResponse(data, textStatus, jqXHR, hostIndx) { alert(data); },
               error: handleLedResponse(jqXHR, textStatus, errorThrown, hostIndx) { alert(errorThrown); }
            })
    }
}

function handleLedResponse(textStatus, hostIndx) {
    var curSpan = document.getElementById('col_host_' + hostIndx);
    if (textStatus === 200 || textStatus === 204) {
        curSpan.innerHTML = ledTypes.green;
    } else if (textStatus === 500 || textStatus === 404) {
        curSpan.innerHTML = ledTypes.red;
    } else if (textStatus === 300 || textStatus === 301 || textStatus === 302) {
        curSpan.innerHTML = ledTypes.yellow;
    }

运行此脚本的触发器:

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

响应也会呈现给index.html

1 个答案:

答案 0 :(得分:0)

试试这段代码。

for(; hostIndx < hosts.length; hostIndx++) {  第一个问题是for循环语法。你的循环不起作用。在循环中尝试console.log(hostIndx)

   function collectionChecking() {

    for(; hostIndx < hosts.length; hostIndx++) {

           $.ajax({
                url: hosts[hostIndx],
                dataType: "jsonp",
                jsonpCallback: "_stdout",
                cache: false,
                crossDomain: true,
                timeout: 10000,
                success: function(data, textStatus, jqXHR) { handleLedResponse(textStatus, hostIndx) },
                  error: function(data, textStatus, jqXHR) { handleLedResponse(textStatus, hostIndx); }
            })
    }
}