2016-04-26 19 views

答えて

2

私が見つけたもっとも簡単な方法の1つは、ファイルを取得し、ダウンロードが準備ができたら別の関数を呼び出す関数を作成することです。 下の例では、 "test.txt"ファイルの内容が読み込まれると、それはpre要素に表示されます。

<html> 
<body> 
<pre id="output"></pre> 
</body> 
<script type="text/javascript"> 

function get_file(url, callback) 
{ 
    xmlhttp=new XMLHttpRequest(); 
    xmlhttp.open("GET", url, true); 
    xmlhttp.onreadystatechange = function() 
    { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
     { 
      callback(xmlhttp.responseText); 
     } 
    } 
    xmlhttp.send(); 
} 

get_file("test.txt", function(response) 
{ 
    document.getElementById("output").innerHTML=response; 
}); 

</script> 
</html> 

重要

あなたのXMLHttpRequestの同期を行いたい場合は、単に

xmlhttp.open("GET", url, false); 

にライン

xmlhttp.open("GET", url, true); 

を変更しかし、それは犠牲にして来ますデータが読み込まれるまであなたのウェブページをぶら下げてください。

0

フェッチ使用してみてください: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

それはXMLHttpRequestをより使いはるかに簡単です。その後

、ドキュメントのボディに追加しinsertAdjacentHtmlを使用して、リソースをフェッチしたら:https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

すなわち

fetch("test.json") 
    .then(function(response) { 
      return response.json(); 
     }) 
    .then(function(json) { 
      document.body.insertAdjacentHtml("afterbegin", "<p>" + json + "</p>); 
     }); 
    .catch(function(error) { 
      console.log('There has been a problem with your fetch operation: ' + error.message); 
      }); 
関連する問題