俗话说的好,说起来容易做起来难,放在编程上说是看起来容易编起来难,虽说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>

以上就是【用ajax xml的数据读取的HelloWorld程序】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论