1、定义xhr变量
2、等待页面渲染完毕后创建xhr
function createXmlHttpRequest() {
if (window.XMLHttpRequest) {
//其他
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
3、设置回调,发送请求
function getMenu() {
xmlHttp.onreadystatechange = displayMenu;
xmlHttp.open("GET", "getMenu");
xmlHttp.send(null);
}
注:post请求应加上请求头
xhr.open("POST", "user/login");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("username=" + username + "&password=" + password);