2、使用innerHTML属性创建动态内容——ajax基础笔记
使用innerHTML属性创建动态内容如果结合作用HTML元素的innerHTML属性,responseText属性会变得非常有用。
innerHTML.html清单:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Using responseText with innerHTML</title> <script type="text/javascript">var xmlHttp;function createXMLHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }} function startRequest() { createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", "innerHTML.xml", true); xmlHttp.send(null);} function handleStateChange() { if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) {//把responseText直接赋给innerHTML document.getElementById("results").innerHTML = xmlHttp.responseText; } }}</script></head><body> <form action="#"> <input type="button" value="Search for Today's Activities" /> </form> <div id="results"></div></body></html> innerHTML.xml清单:
<table border="1"> <tbody> <tr> <th>Activity Name</th> <th>Location</th> <th>Time</th> </tr> <tr> <td>Waterskiing</td> <td>Dock #1</td> <td>9:00 AM</td> </tr> <tr> <td>Volleyball</td> <td>East Court</td> <td>2:00 PM</td> </tr> <tr> <td>Hiking</td> <td>Trail 3</td> <td>3:30 PM</td> </tr> </tbody></table>运行结果:
http://dl.iteye.com/upload/attachment/157386/a081184a-cb33-3b10-b1c1-4e2ef28818f0.gif
使用responseText和innerHTML可以大简化向页面增加动态内容的工作。遗憾的是,这种方法存在一些缺陷。因为innerHTML属性不是HTML元素的标准属性,所以与标准兼容的浏览器不一定提供这个属性的实现。不过,当前大多数浏览器支持innerHTML属性。但是,IE是率先使用innerHTML的浏览器,但它的innerHTML实现反而最受限制。现在许多浏览器都将innerHTML属性作为所有HTML元素的读/写属性。与此不同的是,IE则有所限制,在表和表行之类的HTML元素上innerHTML属性仅仅是只读属性,从一定程度上看这就是限制了它的使用。
页:
[1]