ajax サーバー応答コンテンツ:
XMLHttpRequest オブジェクトの responseText または responseXML 属性を使用して、サーバーから応答コンテンツを取得します。
2 つの属性関数リストは次のとおりです。
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.php.cn/" /> <title>php中文网</title> <script> function loadXMLDoc(){ var xmlhttp; if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("show").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","demo/ajax/txt/demo.txt",true); xmlhttp.send(); } window.onload=function(){ var obt=document.getElementById("bt"); obt.onclick=function(){ loadXMLDoc(); } } </script> </head> <body> <div id="show"><h2>原来的内容</h2></div> <button type="button" id="bt">查看效果</button> </body> </html>サーバーからの応答が XML であり、XML オブジェクトとして解析する必要がある場合は、responseXML 属性を使用する必要があります。その使用法は次のように示されます。
responseXML | XML形式でレスポンスデータを取得します。 |
サーバーからの応答コンテンツが XML でない場合は、responseText 属性を使用して取得します。この属性の戻り値は文字列形式です。使用法は次のように示されます: document.getElementById("show").innerHTML=xmlhttp.responseText;完全なコード例: | ボタンをクリックしてテキスト ファイルの内容を取得し、responseText 属性を通じて div に書き込みます。 2. responseXML 属性: |
var xmlDoc = xmlhttp.responseXML;responseXML 属性の XML オブジェクトは、完全なオブジェクト インスタンスは次のとおりです: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="author" content="http://www.php.cn/" /> <title>php中文网</title> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var xmlDoc = xmlhttp.responseXML; var str = ""; var targets = xmlDoc.getElementsByTagName("target"); for (index = 0; index < targets.length; index++) { str = str + targets[index].childNodes[0].nodeValue + "<br>"; } document.getElementById("show").innerHTML = str; } } xmlhttp.open("GET", "demo/ajax/xml/XML.xml", true); xmlhttp.send(); } window.onload = function () { var obt = document.getElementById("bt"); obt.onclick = function () { loadXMLDoc(); } } </script> </head> <body> <div> <div id="show"></div> <input id="bt" type="button" value="查看效果"/> </div> </body> </html>次のセクション なし |