JavaScript 使用XMLHttpRequest发送异步请求

第一种:发送get请求。

var xhr = new XMLHttpRequest();
xhr.open('GET',url);//url为请求地址
xhr.responseType = 'json';
xhr.onload = function () {
   // 请求结束后,在此处写处理代码
};
xhr.onerror = function(){//请求错误
    console.log('xhr error');
}

xhr.send();

第二种:发送post请求。

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//发送合适的请求头信息
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        // 请求结束后,在此处写处理代码
    }
}
xhr.send("foo=bar&lorem=ipsum");