代码整体:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>初识Ajax开发</title>
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById('btn');
btn.onclick = function(){
var uname = document.getElementById('username').value;
var pw = document.getElementById('password').value;
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft");
}
console.log(xhr.readyState + '----------1-----------');
var param = 'username='+uname+'&password='+pw;
xhr.open('post','04post.php',true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(param);
console.log(xhr.readyState + '----------2-----------');
xhr.onreadystatechange = function(){
console.log(xhr.readyState + '----------3-----------');
if(xhr.readyState == 4){
if(xhr.status == 200){
alert(xhr.responseText);
}
}
}
}
}
</script>
</head>
<body>
<form>
用户名:
<input type="text" name="username" id="username"><span id="info"></span>
<br> 密码:
<input type="text" name="password" id="password">
<input type="button" value="登录" id="btn">
</form>
</body>
</html>
代码分段解读:
1.创建XMLHttpRequest对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();//标准
}else{
xhr = new ActiveXObject("Microsoft");//IE6及以下适用
}
// readyState=0**表示xhr对象创建完成**
console.log(xhr.readyState + '----------1-----------');
2.准备发送
参数一:请求方式(get获取数据;post提交数据)
参数二:请求地址
参数三:同步或者异步标志位,默认是true表示异步,false表示同步
post请求参数通过send传递,不需要通过encodeURI()转码
必须设置请求头信息
var param = 'username='+uname+'&password='+pw;
xhr.open('post','04post.php',true);
3.执行发送动作
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(param);//post请求参数在这里传递,并且不需要转码
4.指定回调函数
xhr.onreadystatechange = function(){
console.log(xhr.readyState + '----------3-----------');
if(xhr.readyState == 4){
if(xhr.status == 200){
// 这里的200表示数据是正常的
alert(xhr.responseText);
}
}
}
代码执行结果:
结果分析:
readyState:
1表示已经发送了请求
2 浏览器已经收到了服务器响应的数据
3 正在解析数据
4 数据已经解析完成,可以使用了 (但是该数据不一定正常)
http的常见状态码:
200 表示响应成功
404 没有找到请求的资源
500 服务器端错误
200表示服务器返回的数据是正常的,不是200的话表示数据是错误的