ajax请求xml、json和txt文件

1.ajax请求xml

//xml代码
<?xml version='1.0' encoding="utf-8"?>
<中国>
		<陕西省>
				<西安市>这座城市很nice</西安市>
				<宝鸡市>这座城市之前叫 陈仓</宝鸡市>
		</陕西省>
		<甘肃省>
				<兰州市></兰州市>
		</甘肃省>
		<四川省>
				<成都市></成都市>
		</四川省>
</中国>

//js代码
           window.onload=function(){
				var btn = document.getElementById("btn1");
				btn.onclick=function(){
					//创建ajax对象
					var xhr = new XMLHttpRequest();
					//准备发送
					xhr.open("GET","china.xml",true);
					//发送
					xhr.send();
					//服务器响应
					xhr.onreadystatechange=function(){
						if(xhr.readyState == 4 && xhr.status == 200){
							var data1 = xhr.responseXML;
							var china = data1.getElementsByTagName("中国");
							var text = china[0].children[0].children[0].firstChild.wholeText;
							console.log(text);
						}
					};
				};
			}

2.ajax请求json

//json代码
[
	{
		"name":"张国立",
		"sex":"男",
		"ege":"50"
	},
	{
		"name":"邓婕",
		"sex":"女",
		"ege":"??"
	},
	{
		"name":"邓超",
		"sex":"男",
		"ege":"39"
	}
]

//js代码
          window.onload=function(){
				var btn = document.getElementById("btn");
				btn.onclick=function(){
					//创建XMLHttpRequest对象
					var xhr = null;
					if(window.XMLHttpRequest){
						xhr = new XMLHttpRequest();
					}else{
						xhr = new ActiveXObject();
					}
					//发送要求
					xhr.open("GET","ajax.json",true);
					//发送
					xhr.send();
					//服务器相应
					xhr.onreadystatechange=function(){
						if(xhr.readyState == 4 && xhr.status == 200){
							console.log(xhr.responseText);
							var obj = JSON.parse(xhr.responseText);
							console.log(obj);
						}
					}
				}
			}

3.ajax请求txt

//txt
[
	{
		"name":"张国立",
		"sex":"男",
		"ege":"50"
	},
	{
		"name":"邓婕",
		"sex":"女",
		"ege":"??"
	},
	{
		"name":"邓超",
		"sex":"男",
		"ege":"39"
	}
]

//js
           window.onload=function(){
				var btn = document.getElementById("btn");
				btn.onclick=function(){
					//创建ajax对象
					var xhr = null;
					if(window.XMLHttpRequest){
						xhr = new XMLHttpRequest();
					}else{
						xhr = new ActiveXObject();
					}
					//发送要求
					xhr.open("GET","ajax.txt",true);
					//发送
					xhr.send();
					//服务器响应
					xhr.onreadystatechange=function(){
						if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)){
							console.log(xhr.responseText);
							var obj = JSON.parse(xhr.responseText);
							console.log(obj);
						};
					};
				};
			}

猜你喜欢

转载自blog.csdn.net/lipeiwen1998/article/details/107726409
今日推荐