0%

ajax

是什么

AJAX全称是Async JavaScript and XML,即异步的JavaScript和XML,是一种创建交互式网页应用的网页开发技术,可以在不重新加载整个网页的情况下,与服务器交换数据,并且更新部分网页

实现过程

实现Ajax异步交互需要服务器逻辑进行配合,需要完成以下步骤:

  • 创建Ajax的核心对象XMLHttpRequest对象
  • 通过XMLHttpRequest对象的open()方法与服务器建立连接
  • 构建请求所需的数据内容,并通过XMLHttpRequest对象的send()方法发送给服务器端
  • 通过XMLHttpRequest对象提供的onreadystatechange事件监听服务端你的通信状态
  • 接受并处理服务端向客户端响应的数据结果
  • 将处理结果更新到HTML页面中

创建XMLHttpReauest对象

通过XMLHttpRequest()构造函数用于初始化一个XMLHttpRequest实例对象

1
const xhr=new XMLHttpRequest()

与服务器端建立连接

通过XMLHttpRequest对象的open()方法与服务器建立连接

1
xhr.open(method,url,[async][,user][,password])

method:表示当前请求方式,常见的有GET,POST

url:服务端地址

async:布尔值,表示用于异步执行操作,默认为true

user:可选的用户名用于认证用途,默认为null

password:可选的密码用于认证用途,默认为null

给服务端发送数据

通过XMLHttpRequest对象的send()方法,将客户端页面的数据发送给服务端

1
xhr.send([body])

body:在XHR请求中要发送的数据体,如果不传递数据则为null

如果使用GET请求发送数据,需要注意:

  • 将请求数据添加到open()方法的url地址中
  • 发送请求数据的send()方法中参数设置为null

绑定onreadystatechange事件

onreadystatechange事件用于监听服务器端的通信状态,主要监听的属性为XMLHttpRequest.readyState,关于XMLHttpRequest.readyState属性有五个状态

只要readyState属性值一变化,就会触发一次readyStatechange事件,XMLHttpRequest.reponseText属性用于接收服务器端的响应结果

封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function ajax(options){
//创建一个XMLHttpRequest对象
const xhr=new XHRHttpRequest()
//初始化参数内容
options=options||{}
options.type=(options||'GET').toUpperCase
options.dataType=options.dataType||'json'
const params=options.data

//发送请求
if(options.type==='GET'){
xhr.open('GET',options.url+"?"+params,true)
xhr.send(null)
}else if(options.type==='POST'){
xhr.open('POST',options.url,true)
xhr.send(params)
}
//接收请求
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
let status=xhr.status
if(status>=200&&status<300){
options.success&&options.success(xhr.responseText,xhr,responseXML)
}else{
options.fail&&options.fail(status)
}
}
}



}

使用

1
2
3
4
5
6
7
8
9
10
11
12
ajax({
type:'post',
dataType:'json',
data:{},
url:'https://xxx',
success:function(text,xml){
console.log(text)
},
fail:function(status){
console.log(status)
}
})