XMLHttpRequest 是 AJAX 的基础。
XMLHttpRequest 对象
所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
创建 XMLHttpRequest 对象
所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。创建 XMLHttpRequest 对象的语法:
variable=new XMLHttpRequest();老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:variable=new ActiveXObject("Microsoft.XMLHTTP");为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
下面的使用ActiveXObject("Microsoft.XMLHTTP")创建xmlHttp就可以,弄了半天是浏览器的问题。
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
url="http://127.0.0.1:27100/Terminal?t=FaceValidateWithIdCard&serviceId=32101412130&timeout=60&s="+Math.random()*10;//alert(url)
xmlHttp.onreadystatechange=function() { if (xmlHttp.readyState==4 && xmlHttp.status==200) { var a=xmlHttp.responseText; //alert(a) } } xmlHttp.open("GET",url,true); //第三个参数是同步异步,主线程只能异步 // alert("1") //xmlhttp.onreadystatechange=favorOK;//发送事件后,收到信息了调用函数 xmlHttp.send(); // alert("2")