(1) XMLHttpRequest (XHR)
在不刷新整个页面的时候, 部分更新数据
var xhr=new XMLHttpRequest();
<script type="text/javascript">
var xhr=new XMLHttpRequest();
//创建一个对象
console.log(xhr);
</script>
(2) 请求 发送
xhr.open(http method, url , false/true); 准备
http method: get / post
url: 路径
false: 异步 true: 同步
xhr.send(参数); 发送
参数: 如果是post :那么要填写参数
如果是get: 那么不需要 直接是 xhr.send(null);
(3) 响应
responseText 响应主体
status 响应码
statusText 响应码说明
status:
1**: continue
200: ok
3**: redirect 重定向
301 302 304
4**: client 客户端问题
401 404
5**: Server 服务器端问题
500 503
Apple网站请求和响应查看:
(4) 请求-响应间的过程 触发readystatechange事件
//调用监控事件
xhr.onreadystatechange=function(){
//如果状态为4 且 响应码为200 说明有正确的回复
if (xhr.readyState ==4 ) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}else{
console.log(xhr.status);
}
}
}
(5) 练习
<script type="text/javascript">
var div=document.getElementById("div");
var xhr=new XMLHttpRequest();
xhr.open("get","a.php?name=jessica",false);
xhr.send(null);
if (xhr.status==200) {
console.log(xhr.status+":"+xhr.statusText);
div.innerHTML=xhr.responseText;
}else{
console.log(xhr.responseText);
}
</script>
<?php
$name=$_GET['name'];
echo "My Name is:".$name;
?>
如果改变
//url 错误
xhr.open("get","b.php?name=jessica",false);