原生AJAX请求
AJAX简介
- Ajax 是 Asynchronous JavaScript XML 的缩写,被译为异步 JavaScript 和 XML。(现在不用XML了,一般都使用json)
- 使用AJAX时,HTML 页面能够快速地将数据逐步更新显示在用户界面上,不需要重载(刷新)整个页面。最大的优势:无刷新获取数据
- AJAX不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式
Ajax 的核心对象
- 实现 Ajax 异步交互的核心就是 XML.httpRequest 对象,该对象为客户端提供了在客户端和服务器之间传输数据的功能。
- XML.HttpRequest 对象提供了一个通过 URL 来获取数据的简单方式,并且不会使整个页面刷新。这使得网页只更新一部分页面而不会打扰到用户。
- XML.HttpRequest 对象最初由微软设计,随后被 Mozilla、Apple 和 Google 采纳。如今,该对象已经被 W3C 组织标准化。通过该对象,可以很容易地得到一个 URL.上 的资源数据。尽管名字里有 XML,但 XML HttpRequest 对象可以得到所有类型的数据资源,并不局限于 XML 格式的数据。
实现 Ajax 的执行步骤
实现 Ajax 异步交互需要服务器端逻辑进行配合,而作为客户端的 HTML 页面需要完成以下步骤:
- 创建 Ajax 的核心对象 XML.HttpRequest 对象
- 通过 XML.HttpRequest 对象的 **open()**方法与服务器端建立连接
- 构建请求所需的数据内容,并通过 XML.HttpRequest 对象的 send()方法发送给服务器端
- 通过 XMLHttpRequest 对象提供的 onreadystatechange 事件监听服务器端的通信状态,
接收并处理服务器端向客户端响应的数据结果将处理结果更新到页面中
具体实现
简单get和post请求的服务器配置
服务器是node下的一个轻量级的框架express,具体设置:
const server = require('express')
const app = server();
app.get('/server',(request,response)=>{
//设置响应头,允许跨域
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应体
response.send('hello ajax-2')
});
app.all('/server',(request,response)=>{
//设置响应头,允许跨域
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应体
response.send('hello ajax')
});
get请求
- const xhr = new XMLHttpRequest() 创建对象
- xhr.open() 与服务器建立连接,两个参数:请求方法和url
- xhr.send() 发送请求
- xhr.onreadychange 接收返回结果并写在当前页面中
const btn = document.querySelector('.btn')
const result = document.querySelector('#result')
btn.onclick = function (){
// 1.创建对象
const xhr = new XMLHttpRequest()
// 2.初始化 设置请求的方法和url
xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=300')
// 3.发送
xhr.send()
// 4.时间绑定 处理服务端返回的结果
// on when 当...的时候
// readystate 是 xhr 对象中的属性,表示状态0 1 2 3 4
// change改变的时候
xhr.onreadystatechange = function (){
//判断 如果状态为4的时候 服务端返回了所有的结果
if(xhr.readyState === 4){
// 响应状态码2开头的都是成功
if(xhr.status >= 200 && xhr.status<300){
// 处理结果
// 1.响应行
result.innerHTML = xhr.response
}else{
}
}
}
}
POST请求
post请求可以发送也可以接收。比get请求多一步设置请求头:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
具体实现如下:
const result = document.querySelector('#result')
result.addEventListener('onkeydown',function (){
console.log("test")
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.初始化 设置类型和url
xhr.open('POST','http://127.0.0.1:8000/server')
// 设置请求头 一般把身份校验的信息放在请求头中 发送给服务器进行校验
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 3.发送
xhr.send('a=100&b=200')
// 4.事件绑定
xhr.onreadystatechange = function (){
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
//处理服务端返回的结果
result.innerHTML = xhr.response
}
}
}
})
发送JSON格式数据的服务器设置
其实就是多了data对象的设置
然后要对json对象进行JSON.stringify(data)转换为字符串
app.all('/json-server',(request,response)=>{
//设置响应头,允许跨域
response.setHeader('Access-Control-Allow-Origin','*')
response.setHeader('Access-Control-Allow-Headers','*')
const data = {
name:'lsr'
}
// 对字符串进行转换
let str = JSON.stringify(data)
//设置响应体
response.send(str)
});
获得JSON格式数据的请求的发送
其实就是多了xhr.responseType = 'json’这句声明
然后在onreadychange中可以获取在服务器端设置的数据
const result = document.querySelector('#result')
window.onkeydown = function (){
const xhr = new XMLHttpRequest()
xhr.responseType = 'json'
xhr.open('GET','http://127.0.0.1:8000/json-server')
xhr.send()
xhr.onreadystatechange = function (){
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
console.log(xhr.response.name)
result.innerHTML = xhr.response.name
}
}
}
}
延时响应
服务器端
app.get('/delay',(request,response)=>{
//设置响应头,允许跨域
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应体
setTimeout(()=>{
response.send('延时响应')
},3000)
});
在服务器端设置了setTimeout,有可以拥有一个timeout的属性使得服务器有一个延迟响应的效果,例如定时出现图片等效果可以用这种方法来实现。
const btn =document.querySelector('button')
const result = document.querySelector('#result')
btn.addEventListener('click',function (){
const xhr = new XMLHttpRequest()
xhr.timeout = 2000;
xhr.open('GET','http://127.0.0.1:8000/delay')
xhr.send()
xhr.onreadystatechange = function (){
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
result.innerHTML = xhr.response
}
}
}
})