您的位置:首页 > Web前端 > JavaScript

Ajax获取XML数据--原生JavaScript实现

2017-11-29 17:05 706 查看
获取XML数据的时候,要注意在服务器端要在http协议头部中指定content-type为text/xml,否则,客户端请求之后得到的是一个普通文本(text),即使服务器端提供的是一个标准XML格式的数据。客户端在接收响应的时候,使用xhr.responseXML,这个时候,只能辨认XML,而不能处理普通文本。

先看index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" name="button" value="点击出诗" onclick="fetch()">
<div id="msg"></div>
</body>
<script>
function fetch(){
var div=document.getElementById("msg");
var input=document.getElementsByName("button")[0];
var xhr=new XMLHttpRequest();

xhr.onreadystatechange=function(){
if(this.readyState==4 && this.status == 200){
alert(typeof this.responseXML);
div.innerHTML=this.responseXML.getElementsByTagName('title')[0].childNodes[0].nodeValue;
}
}

xhr.open("GET","index.php","true");
xhr.send(null);
}
</script>
</html>


  

index.php

<?php header('content-type: text/xml; charset=utf-8'); ?>
<?xml version='1.0' encoding='utf-8'?>
<book>
<poetry>
<title>登岳阳楼</title>
<author>白居易</author>
<content>昔闻洞庭水,今上岳阳楼。</content>
</poetry>
<poetry>
<title>旅宿</title>
<author>杜牧</author>
<content>旅馆无良伴,凝情自悄然。</content>
</poetry>
</book>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐