2016-12-20 14 views
0

これは私が "stat.php"へのリクエストをしようとする私のメインコードです。XmlHttpRequestが機能しない、何も返されない

メインコード

<!DOCTYPE html> 
<html> 
<head> 
    <title>test</title> 
    <meta charset="utf-8" /> 
    <link rel="stylesheet" href="style-index.css" /> 
    </head> 
<body> 
    <script> 
    function test() { 
     var req = new XMLHttpRequest(); 
     req.open('GET', 'http://www.cubeadvisor.fr/stat.php', true); 
     req.send(null); 
     document.getElementById("timer").innerHTML=req.responseText; 
    } 
    </script> 
    <button onclick="test()">Click me</button> 
    <p id="timer"> </p> 
</body> 
</html> 

stat.php

<?php header('Access-Control-Allow-Origin: *'); 
echo "test"; ?> 

何も返されなかったと私はすべてのエラーを見つけることができません。 私はこの問題を解決するためにあなたの助けを求めています。

+1

あなたは、サーバーの応答を待つ必要があります。 – SLaks

+0

jQueryを使用できますか? –

+0

リクエストからの応答はどこで処理しますか? – TheJim01

答えて

3

これは非同期イベントです。応答がサーバーから取得されるまで待機してから、更新機能を起動するには、onreadystatechangeイベントを使用する必要があります。

req.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
    document.getElementById("timer").innerHTML = this.responseText; 
    } 
}; 

ワーキングスニペット

<script> 
 
    function test() { 
 
    var req = new XMLHttpRequest(); 
 
    req.open('GET', 'http://www.cubeadvisor.fr/stat.php', true); 
 
    req.send(null); 
 
    req.onreadystatechange = function() { 
 
     if (this.readyState == 4 && this.status == 200) { 
 
     document.getElementById("timer").innerHTML = this.responseText; 
 
     } 
 
    }; 
 
    } 
 
</script> 
 
<button onclick="test()">Click me</button> 
 
<p id="timer"></p>

関連する問題