Ajax:
异步无刷新技术。能够请求后台发送和获取数据,而无需卸载页面(刷新页面)。
核心对象:
XMLHttpRequest对象
var xhr = new XMLHttpRequest()
1、在使用xhr对象时,先必须调用open()方法,它接收三个参数:要发送的请求类型(get、post)、请求的url和表示是否异步(true、false)。open()方法并不会真正发送请求,而是启动一个请求以发送。
2、通过send()方法进行发送请求,send()方法接受一个参数,作为请求主体发送的数据。如果不需要则,必须填null。执行send()方法之后,请求就会发送到服务器上 。
发送请求的步骤:
1、得到XMLHttpRequest对象
var xhr = new XMLHttpRequest()
2、准备请求 open(请求类型GET/POST,请求的url,是否异步)
xhr.open(请求类型GET、POST,请求的url,是否异步);
3、发送请求 send([参数])
xhr.send([参数])
注:如果是GET请求,请求的参数设置在url后面,所以send(null)
如果是POST请求,无参数设置为null,有参数则设置参数即可
4、判断响应状态,得到后台响应
xhr.responseText;
<script type="text/javascript">
// 1、得到XMLHttpRequest对象
var xhr = new XMLHttpRequest();
console.log(xhr);
// 2、准备请求 open(请求类型GET/POST,请求的URL,是否异步)
xhr.open("POST","js/data.json",false); // 同步请求
console.log("open...");
// 模拟表单提交
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 3、发送请求 send(参数)
//xhr.send("uname=zhangsan&upwd=123456"); // Post请求有参数,则设置
xhr.send("uname=zs&upwd=123");
console.log("send...");
// 4、判断响应状态,得到后台响应得到后台响应 xhr.responseText;
if (xhr.status == 200) {
var responseTxt = xhr.responseText;
console.log(responseTxt);
} else {
alert("状态码:" + xhr.status + ",错误信息:" + xhr.responseText);
}
console.log("测试...");
</script>