2016-10-06 5 views
1

xamppを使用しているローカルホスト上でindex.htmlを実行している場合はエラー: index。 HTML:17キャッチされないInvalidStateError:失敗した 'XMLHttpRequestを' オン 'に送信' を実行するには:オブジェクトの状態でなければなりませんOPENED.sendAjax @ index.htmlを:17onclickする@のindex.html:Ajaxエラー:index.html:17 Uncaught InvalidStateError: 'XMLHttpRequest'で 'send'を実行できませんでした。オブジェクトの状態はOPENED.sendAjaxである必要があります。

:ここ

28は、index.htmlファイルでありますここで

<!DOCTYPE HTML> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Show Ajax</title> 

<script> 
var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function() { 
    if(xhr.readyState === 4){ 
      document.getElementById('ajax').innerHTML = xhr.responseText; 
    } 
    xhr.open('GET', 'data.html'); 

}; 
function sendAjax(){ 
     xhr.send(); 
     document.getElementById('load').style.display = "none"; 

    } 
</script> 

</head> 

<body> 

<h1>Bring on ajax</h1> 
<button id="load" onClick="sendAjax()">bring it</button> 
<div id="ajax"> 

</div> 

</body> 
</html> 

はData.HTMLにファイルです。

<!DOCTYPE HTML> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Untitled Document</title> 
</head> 

<body> 
<p> Hello I'm Ajax, came here on your request</p> 
</body> 
</html> 

答えて

0

readyStateハンドラ内でリクエストを開くことはできません。リクエストが行われるときにのみハンドラが起動されるため、ハンドラが呼び出される前にリクエストを開く必要があります。それは機能の外で、それの後に意味します。

あなたがそう

function sendAjax(){ 

    var xhr = new XMLHttpRequest(); 

    xhr.onreadystatechange = function() { 
     if(xhr.readyState === 4 && xhr.status === 200) { 
      document.getElementById('ajax').innerHTML = xhr.responseText; 
     } 
    }; 

    xhr.open('GET', 'data.html'); 
    xhr.send(); 

    document.getElementById('load').style.display = "none"; 
} 
+0

おかげで男を行うにはない非常に良い理由がない限り、あなたはまた、一般的に、sendAjax関数の呼び出しごとに新しいリクエストオブジェクトを作成する必要があります!あなたは正しいです、私はreadystateの中でリクエストを開いていました、私は単に機能をオフにして、今は正常に動作します。 私はそれを感謝します。 :) –

+0

@Jazib_Prince - ようこそ – adeneo

関連する問題