「AJAX」コールバック(callback)関数のサンプル

書式
loadDoc('テキスト名’, callback関数名)
コールバック関数は他の関数に引数として渡される関数で、外側の関数で何らかの処理やアクションを実行します。
使用例

<!DOCTYPE html>
<html>
<body>

<div id="sample">

<h2>XMLHttpRequestオブジェクト</h2>

<button type="button" onclick="loadDoc('ajax_info.txt', cftFunction)">変更
</button>
</div>

<script>
function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cftFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
function cftFunction(xhttp) {
  document.getElementById("sample").innerHTML =
  xhttp.responseText;
}
</script>
</body>
</html>

 

Ajax

Posted by arkgame