AJAX の例

まず例を見てみましょう:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
     xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
    xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
<button type="button" onclick="loadXMLDoc()">修改内容</button>
</body>
</html>


分析例

上記の AJAX アプリケーションには div とボタンが含まれています。

div セクションは、サーバーからの情報を表示するために使用されます。ボタンをクリックすると、loadXMLDoc() という関数が呼び出されます。

<!DOCTYPE html>
<html>
<body>
  <div id="myDiv"><h2>Let AJAX change this text</h2></div>
  <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

次に、ページの head セクションに <script> タグを追加します。このタグには、loadXMLDoc() 関数が含まれています:

<head>
<script>
    function loadXMLDoc()
    {
    .... AJAX script goes here ...
    }
</script>
</head>

注: ajax_info.txt および HTML ファイルを実行するには、同じ仮想ホストまたは同じ Web サイトに配置する必要があります。

学び続ける
||
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/asset/demo.ajax.php?dm=txt",true); //
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>使 AJAX </h2></div>
<button type="button" onclick="loadXMLDoc()"></button>
</body>
</html>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
图片放大关闭