Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax发送请求</title>
</head>
<script>
//1.声明一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//2.输入网址
xhr.open('GET','http://localhost:63342/web/Ajax/time.php');
//3.发送
xhr.send();
</script>
<body>
</body>
</html>
Ajax接收响应
chrome不支持打开本地的ajax请求,可以用Firefox
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax接收请求</title>
</head>
<script>
//1.声明一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// xhr.addEventListener('readystatechange',function () {
// console.log(this.readyState)
// //1,2,3,4
// })
//2.输入网址
xhr.open('GET','http://localhost:63342/web/Ajax/time.php');
//3.发送
xhr.send();
//不只是响应时触发,当状态改变就触发
xhr.addEventListener('readystatechange',function () {
//接收请求,处理请求
if(this.readyState !==4){
console.log(this.responseText)
}
console.log(this.readyState)
//2,3,4
})
</script>
<body>
</body>
</html>
Ajax接收响应2
html中提供了一种更简便的方式,但是目前对浏览器兼容不是很好
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax接收请求</title>
</head>
<script>
//1.声明一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// xhr.addEventListener('readystatechange',function () {
// console.log(this.readyState)
// //1,2,3,4
// })
//2.输入网址
xhr.open('GET','http://localhost:63342/web/Ajax/time.php');
//3.发送
xhr.send();
//4.获取并处理 onload是HTML5中提供的XMLHttpRequest version2.0的版本
xhr.onload=function(){
console.log(this.responseText)
console.log(this.readyState)
//2,3,4
}
</script>
<body>
</body>
</html>
readyState详解
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>readyState</title>
</head>
<script>
var xhr = new XMLHttpRequest();
console.log(xhr.readyState);
// => 0
// 初始化 请求代理对象
xhr.open('GET','http://localhost:63342/web/Ajax/time.php');
console.log(xhr.readyState);
// => 1
//open 方法已经调用,建立一个与服务器特定端口的链接
xhr.send();
//不只是响应时触发,当状态改变就触发
xhr.addEventListener('readystatechange',function () {
switch (this.readyState){
case 2:
console.log(this.getAllResponseHeaders());
/*cache-control: private, must-revalidate
content-length: 22
content-type: application/octet-stream
date: Sat, 20 Jul 2019 03:13:05 GMT
last-modified: Sat, 13 Jul 2019 12:55:44 GMT
server: WebStorm 2017.1.2
x-content-type-options: nosniff
x-frame-options: SameOrigin
x-xss-protection: 1; mode=block
全部响应头*/
console.log(this.getAllResponseHeaders('server'));
//响应头的具体一部分
console.log(this.readyState);
break;
// =>2
// 已经接收到了响应报文的响应头,接收不到响应体
case 3:
console.log(this.readyState);
break;
// =>3
// 正在下载响应报文的响应体,有可能响应体为空,或不完整
//在这里处理响应体不可靠
case 4:
console.log(this.readyState);
console.log(this.responseText);
break;
// =>4 响应体已经完整
}
})
</script>
<body>
</body>
</html>