用户登录
用户注册

分享至

用ajax xml的数据读取的HelloWorld程序

  • 作者: 彭先森46727826
  • 来源: 51数据库
  • 2021-09-21
俗话说的好,说起来容易做起来难,放在编程上说是看起来容易编起来难,虽说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>
软件
前端设计
程序设计
Java相关