DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX基礎知識 >> 用ajax xml的數據讀取的HelloWorld程序
用ajax xml的數據讀取的HelloWorld程序
編輯:AJAX基礎知識     
俗話說的好,說起來容易做起來難,放在編程上說是看起來容易編起來難,雖說ajax裡面沒有什麼新的技術,只是思想的轉變和舊技術的整合,但是動起手來還是問題多多,首先就是我經常使用的是火狐浏覽器,馬上就碰到了innerText在火狐裡面不被兼容的問題,剛開始找不到原因,後來突然反應過來可能是兼容的問題,百度一下,果不其然,在ff裡面要使用textContent方法,且一定要遵從w3c標准使用getElementById獲取div,不能圖省事直接寫id,在IE裡面行的通,在火狐和其他浏覽器就不知道了,還是按標准來吧,這樣也有可讀性嘛^_^
代碼:
復制代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Ajax的第一個經典例子Hello World</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();
try{
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "data.xml", true);
xmlHttp.send(null);
}catch(exception){
alert("您要訪問的資源不存在!");
}
}
function handleStateChange(){
if(xmlHttp.readyState == 4){
if (xmlHttp.status == 200 || xmlHttp.status == 0){
// 取得XML的DOM對象
var xmlDOM = xmlHttp.responseXML;
// 取得XML文檔的根
var root = xmlDOM.documentElement;
try
{
// 取得<info>結果
var info = root.getElementsByTagName('info');
// 取字符串
var str_data = info[0].firstChild.data;
//改變div的內容,調用changeText函數,注意IE和FF是不一樣的
changeText(info[0].firstChild.data,'showText');
//innerHTML是一樣的
document.getElementById("showTextHTML").innerHTML = '<strong>' + info[0].firstChild.data + '</strong>';
}catch(exception)
{
}
}
}
}
function changeText(str,element){ //兼容IE和FF的
if(navigator.appName.indexOf("Explorer") > -1){
document.getElementById(element).innerText = str;
} else{
document.getElementById(element).textContent = str;
}
}
</script>
</head>
<body>
<div>
<input type="button" value="return ajax responseXML's value"
onclick="startRequest();" />
</div>
<div id="showText"></div>
<div id="showTextHTML"></div>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved