Ajax 发送请求

< !DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<!--XMLHttpRequest 兼容方案-->
<!--var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP')-->

<script>
//Ajax 就是浏览器提供的一套API,可以通过javascript调用,从而实现通过代码控制请求与相应,实现网络编程

//涉及到Ajax操作的页面“不能”使用文件协议访问(文件的访问方式==》Http://)
// Ajax ===》 XMLHttpRequest

//1:安装浏览器
var xhr=new XMLHttpRequest();
console.log(xhr.readyState);// 0 ==>初始化 请求代理对象

//2:打开浏览器,输入网址
xhr.open('GET','http://day-11.io/time.php.http');
console.log(xhr.readyState);// 1 ==> open 方法已调用,建立一个与服务端特定端口的连接

//3:敲回车键,开始请求
xhr.send();

//4:等待响应
xhr.addEventListener('readystatechange',function () {
switch (this.readyState){
case 2:// 2 ==>已经接受到了响应报文的响应头,可以拿到头
console.log(this.getResponseHeader('server'));
//但还没拿到体
console.log(this.responseText);
break;
case 3:// 3 ==>正在下载响应报文的响应体,有可能响应体为空,也有可能不完整
//在这里处理相应体不保险(不可靠)
console.log(this.responseText);
break;
case 4:// 4 ==> 一切ok (整个响应报文已经完整下载下来了)
console.log(this.responseText);
break;
}
});

//5:看结果
</script>

<script>
var xhr=new XMLHttpRequest();
xhr.open('GET','time.php');
xhr.send();
xhr.addEventListener('readystatechenge',function () {

})
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/lujieting/p/10291246.html
今日推荐