2016-04-22 59 views
0

我想創建一個簡單的網頁應用程序,顯示在一個頁面中的服務器響應,但我很新手。試圖採取服務器響應

當訪問此頁面https://api.minergate.com/1.0/pool/profit-rating時,它會生成一個響應。我如何捕獲它並將其放入我的HTML頁面?

請告訴我最簡單的方法。 :D

我正在用XMLHttpRequest()執行一個簡單的代碼。嚴格按照顯示:

<!DOCTYPE html> 
<html> 
<body> 

<script> 
function test() { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', 'https://api.minergate.com/1.0/pool/profit-rating', true); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4 && xhr.status === 200) { 
     alert(xhr.responseText); 
     alert("GOOD"); 
    } 
    else alert("BAD"); 
    };alert("EXIT"); 
}; 
</script> 
<button onclick='test()'>Click</button> 
</body> 
</html> 

我寫的警報只是爲了測試代碼。但它從來沒有爲我顯示「好」和「壞」。

+0

您需要啓用CORS,請參閱此[post](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-請求資源)獲取更多信息。這是假設您正在嘗試提出請求的網站不是您的網站,而是其他人的網站。 –

+1

你忘了打電話給xhr.send();這實際上會開始您的請求。 – Mathijs

回答

0

這個例子會給你GOOD/BAD輸出,你錯過了xhr.send();

<!DOCTYPE html> 
<html> 
<body> 
<script> 
function test() { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', 'https://api.minergate.com/1.0/pool/profit-rating', true); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4 && xhr.status === 200) { 
     alert(xhr.responseText); 
     alert("GOOD"); 
    } 
    else alert("BAD"); 
    }; 
    xhr.send(null); 
    alert("EXIT"); 
}; 
</script> 
<button onclick='test()'>Click</button> 
</body> 
</html>