PHP 開発の基本チュートリアル onreadystatechange イベント
1. onreadystatechange イベント
リクエストがサーバーに送信されると、いくつかの応答ベースのタスクを?qū)g行する必要があります。
readyState が変更されるたびに、onreadystatechange イベントがトリガーされます。
readyState屬性にはXMLHttpRequestのステータス情報(bào)が格納されます。
XMLHttpRequest オブジェクトの 3 つの重要なプロパティは次のとおりです。
onreadystatechange イベントでは、サーバー応答を処理する準(zhǔn)備ができたときに実行されるタスクを指定します。
readyState が 4 でステータスが 200 の場合、応答が準(zhǔn)備完了であることを意味します
注: onreadystatechange イベントは、readyState の各変更に対応して 5 回 (0 ~ 4) トリガーされます。
2. コールバック関數(shù)を使用する
コールバック関數(shù)は、パラメーターの形式で別の関數(shù)に渡される関數(shù)です。
Web サイトに複數(shù)の AJAX タスクがある場合は、XMLHttpRequest オブジェクトを作成するための標(biāo)準(zhǔn)関數(shù)を作成し、AJAX タスクごとにこの関數(shù)を呼び出す必要があります。
この関數(shù)呼び出しには、URL と、onreadystatechange イベントの発生時(shí)に実行されるタスクが含まれている必要があります (各呼び出しは異なる場合があります):
以下は 2 つの AJAX タスクを含むページを示しています:
Code 5_1.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript"> var xmlhttp; //標(biāo)準(zhǔn)函數(shù) function loadXMLDoc(url,cfunc) { 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=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } function myFunction1() { loadXMLDoc("5_2.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv1").innerHTML=xmlhttp.responseText; } }); } function myFunction2() { loadXMLDoc("5_3.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv2").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <!-- 按下按鈕,調(diào)用myFunction1() --> <div id="myDiv1"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction1()">NO:1 通過 AJAX 改變內(nèi)容</button> <hr/> <!-- 按下按鈕,調(diào)用myFunction2() --> <div id="myDiv2"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction2()">NO:2通過 AJAX 改變內(nèi)容</button> </body> </html>
コード 5_2.txt
AJAX is not a programming language. It is just a technique for creating better and more interactive web applications.
コード 5_3.txt
AJAX 不是新的編程語言,而是一種使用現(xiàn)有標(biāo)準(zhǔn)的新方法。