原生ajax
ajax是一种异步通信的方法,从服务端获取数据,达到局部刷新页面的效果
- 创建
XMLHttpRequest对象; - 调用
open方法传入三个参数 请求方式(GET/POST)、url、同步异步(true/false); - 监听
onreadystatechange事件,当readystate等于4时返回responseText; - 调用send方法传递参数。
<button id="ajaxButton" type="button">Make a request</button>
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest(); // 创建ajax对象
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
// httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = alertContents; // 成功回调
httpRequest.open('GET', 'test.html'); // 请求配置
httpRequest.send(); // 发送请求, POST请求的不同配置,传参
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
//
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
全部readyState状态值都在 XMLHTTPRequest.readyState,如下也是:
- 0 (未初始化) or (请求还未初始化)
- 1 (正在加载) or (已建立服务器链接)
- 2 (加载成功) or (请求已接受)
- 3 (交互) or (正在处理请求)
- 4 (完成) or (请求已完成并且响应已准备好)

浙公网安备 33010602011771号