ajax原理
利用浏览器的内置对象XMLHttpRequest,实现请求服务器,每当XMLHttpRequest的对象发生状态的变化(发送请求,即调用对象的send方法;服务器返回了响应数据),都会触发其onreadystatechange方法的自动调用。
而XMLHttpRequest对象包含了两个属性分别是readyState 和status,当满足了readyState = 4 && status = 200时,表示浏览器获取到了服务器响应返回的数据。

ajax1.png
GET请求的实现
<script>
/**
* ajax就是利用浏览器的内置对象XMLHttpRequest,来实现服务器请求服务器
*/
var xhr = new XMLHttpRequest(); // IE6以及以下的版本不是这个对象。
/**
* xhr在整个请求的过程中, 会发生状态的变化, 每一个状态变化的时候都会触发该方法调用,
* 是浏览器内部自己去给我们触发, 那么在何时会被触发:
* 1. 当xhr.open()方法被调用的时候会被触发, 次吃xhr的readyState状态值为 1
*/
xhr.onreadystatechange = function() {
/**
// 当xhr.open() 那么readyState的状态变为1
if(xhr.readyState == 1) {
console.log('==========================')
}
// 当readyState为2的时候,表示已经和服务器建立了连接, 数据以发送
if(xhr.readyState == 2) {
console.log('******************')
}
// 当readyState为3的时候,表示正在获取数据中
if(xhr.readyState == 3) {
console.log('&&&&&&&&&&&&&&&&********')
}
*/
/**
* 1. 当服务器端返回数据了,readyState的值为4, 但是只能表示服务器返回了数据,可能这个数据不是正确的。
* 例如我们看到的 404、500页面,其实也是服务器给我们响应了,但是并不是我们想要的数据。
* 2.当xhr的status为200的时候,表示返回的数据是正确的数据。
*/
if(xhr.readyState == 4 && xhr.status == 200) {
// 通过 xhr.reponseText获取响应会的数据
console.log(xhr.responseText)
}
}
/**
* 初始化请求:
* 1.第一个参数是请求的方式。
* 2.第二参数是url地址(请求地址)。
* 3.第三个参数boolean的值,true和false.
* true表示按照异步的方式来实现, 不写默认为true, 通常不写。
* false表示按照同步的方式来实现。
*/
xhr.open('GET', 'http://localhost:8081/day52_web_people_war_exploded/ajax?username=zhangsan', true);
// 向服务器发起请求
xhr.send();
console.log('==========================================')
</script>
POST请求的实现
<script>
var xhr = new XMLHttpRequest();
var obj = {age: 10, name: '李四'}
//当readystate状态改变的时候,该方法会被浏览器自动的触发
xhr.onreadystatechange = function() {
// 当有数据返回并且数据争取
if(xhr.readyState == 4 && xhr.status == 200) {
// console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText))
console.log(obj)
}
}
xhr.open('POST', 'http://localhost:8081/day52_web_people_war_exploded/ajax');
// 对于POST来讲,请求头中需要加上如下的信息,可以通过写一个测试表单, 搞一个post请求,通过调试的方式看出来。
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// post请求与get请求携带参数的方式是不一样的, 需要将请求的参数放到send中
xhr.send('username=张安&password=123456&gender=M')
</script>