没有得到来自web-api的回复javascript(没有JS-Framework)

时间:2015-05-13 08:46:58

标签: javascript api

我想从URI获取响应: http://filzmelodie.norhabo.com/chat/api/SalesOnlineStatus

此API将返回一个字符串" 0"或" 1"。
如何在Javascript中获得响应?

这是我的代码:

function getSosFromNorHaBo() {
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', "http://filzmelodie.norhabo.com/chat/api/SalesOnlineStatus");
    script.onreadystatechange = setSosToHuaXing( /*How could I get the response of API?*/ );
    document.body.appendChild(script);
}
function setSosToHuaXing(data){
    alert(data);
}
setInterval(function(){getSosFromNorHaBo()}, 1000 * 1);

我怎样才能获得API的响应?谢谢!

1 个答案:

答案 0 :(得分:0)

创建跨源请求的函数 -

function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        // XHR has 'withCredentials' property only if it supports CORS
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){ // if IE use XDR
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

使用功能 -

function getSosFromNorHaBo() {
    var request = createCORSRequest( "get", "http://filzmelodie.norhabo.com/chat/api/SalesOnlineStatus" );
        if ( request ){
            // Define a callback function
            request.onload = setSosToHuaXing;
            // Send request
            request.send();
        }
    }

function setSosToHuaXing(data){
    alert(data);
}
setInterval(function(){getSosFromNorHaBo()}, 1000 * 1);