Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

原生js加载xml

2019-11-13 00:55:06

<button onclick="javascript:showQBox(this)" >submit</button>

<div id="wrap"></div>
<script>

function showQBox(a){

	/* 2) 封装*/
	var c = function(data){
		var pp = document.getElementById('wrap');
		pp.innerText = data;
	}
	loadXML("GET", "xmlhttp.xml", true, c);
	
	/* 1) 未封装*/
	var xmlhttp;
	// code for IE7+, Firefox, Chrome, Opera, Safari
	if (window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest();
	// code for IE6, IE5
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	
	xmlhttp.open("GET","xmlhttp.xml",true);
	xmlhttp.onreadystatechange = function(){

		if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
			var wrap = document.getElementById('wrap');
			wrap.innerText = xmlToString(xmlhttp.responseXML);
		} else {
			alert("check your xml file");
		}
	}
	xmlhttp.send();
	*/
	
}

/*
 * 不然,出现[object XMLdocument]
 */
function xmlToString(a){
	var serialized;
	try {
		serializer = new XMLSerializer();
		serialized = serializer.serializeToString(a);
	}catch(e){
		serialized = a.xml;
	}
	return serialized;
}

/*
 * 封装函数
 */
function loadXML(method, url, async, callback){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject();
	}
	
	xmlhttp.open(method, url, async);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
			callback(xmlToString(xmlhttp.responseXML));
		} else{
			alert("check your xml. You can try open it directly in server.")
		}
	}
	xmlhttp.send();
}
/*未测
$.ajax({
	type:"GET",
	url:"",
	data:"",
	contentType:"text/json",
	dataType:"text",
	async:true,
	success:function(data){
	}
})
*/
</script>

 

出现问题:

1) xmlhttp.status == 0

因为直接打开html文件,未经过http协议。通过localhost打开正常显示status == 200.

2) 输出[object XMLdocument]

需要转换

3)xmlhttp.responseXML 输出为null

检查xml文件格式是否正确,方法:在localhost打开xml文件,有问题会报错。



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *