JavaScript Ajax 实现学习

创建异步对象:

function createXmlHttp(){
	var xhobj=false;
	try{
		xhobj=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xhobj=new ActiveXObject("Microsoft.XMLHTTP");
		}catch(e2){
			xhobj=false;
		}
	}
	if(!xhobj&&XMLHttpRequest!='undefined'){
		xhobj=new XMLHttpRequest();
	}
	return xhobj;
}

Get 请求:

window.onload=function(){
    document.getElementById("btnClick").onclick=function()
    {
        //第一步创建异步对象。
        var xhr=createXmlHttp();
        xhr.open("get","Modify.ashx",true);
        xhr.setRequestHeader("If-Modified-Since",0);
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                var res=xhr.responseText;
                document.getElementById("divMsg").innerHTML=res;
            }
        }
        //发送请求
        xhr.send(null)
    };
};

Post 请求:

window.onload=function(){
    document.getElementById("btnReg").onclick=function(){
        var xhr=createXmlHttp();
        //定义一个转的界面
        var urlPara="05kjdfgsdjf.ashx"
        xhr.open("post",urlPara,true);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        //5.0设置回调函数。
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200)
            {
                var res=xhr.responseText;            
                //处理数据  ......
            }
        }
        //6.0发送请求 name=james & pwd=123
        xhr.send("name="+document.getElementById("txtName").value+"&pwd="+document.getElementById("txtPwd").value);
    }
}

  

原文地址:https://www.cnblogs.com/lynn-lkp/p/6936279.html