ajax请求基础知识mark
function createXmlHttpRequest(){
if(window.ActiveXObject){ //如果是IE浏览器
return new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
}
//IE7以及以上认识window.XMLHttpRequest,只有IE6不认识。
//IE都认识window.ActiveXObject
var xmlHttpRequest = createXmlHttpRequest();
xmlHttpRequest.onreadystatechange = fn;
xmlHttpRequest.open("get",url,true);
xmlHttpRequest.send(null);
function fn(){
//var data = xmlHttpRequest.responseText; 写这里IE会出现完成该操作所需的数据还不可用的错误
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
var data = xmlHttpRequest.responseText; //在判定状态之后再取返回的数据
//do something
}
}
responseXML与responseText的区别?
responseXML返回的是xml dom对象,通过该对象可以访问xml文件的节点、属性节点、值节点。
而responseText返回的是文本字符串,可以直接打印输出。比如输出的是json 可以通过eval()转换
responseXML在各大浏览器中的使用:
firefox不支持。要想在firefox中返回xml dom对象,可以先返回
responseText,再通过firefox的DOM解析器解析为xml dom对象。具体方法如下:
var parser=new DOMParser();
var xmldom=parser.parseFromString(xmlhttp.responseText,"text/xml");
其中xmlhttp为xmlhttprequest对象。