JS原生ajax小结

//初始化对象并发出XMLHttpRequest请求

var xmlHttp;
function getXmlHttp(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("MICROSOFT.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}

function sendParam(url){
getXmlHttp();

//open的第一个参数是HTTP请求的方法,GET、Post或者Head open的第二个参数是目标URL

//第三个参数只是指定在等待服务器返回信息时,是否继续执行下面的代码。如果为true,则不会,直到服务器返回信息,默认为true

xmlHttp.open("GET","check.php?user="+url,true);
// setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//状态改变的事件触发器
xmlHttp.onreadystatechange = getTxt;

//设置为空,但为必写
xmlHttp.send(null);
}


function getTxt(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){

//返回的值
var sp = document.getElementById("tishi");
sp.innerHTML = xmlHttp.responseText;
}
}
}

// get 请求

// xmlhttp.open("get","ajax.php",true);

// xmlhttp.send();

// post 请求

//xmlhttp.open("post","ajax.php",true);

// xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

// xmlhttp.send("sname=ck");

//最好使用get

原文地址:https://www.cnblogs.com/yanjialin/p/3715196.html