传统方法的缺点:
传统的web交互是用户触发一个http请求服务器,然后服务器收到之后,在做出响应到用户,并且返回一个新的页面,每当服务器处理客户端提交的请求时,客户都只能空闲等待,并且哪怕只是一次很小的交互、只需从服务器端得到很简单的一个数据,都要返回一个完整的HTML页,而用户每次都要浪费时间和带宽去重新读取整个页面。这个做法浪费了许多带宽,由于每次应用的交互都需要向服务器发送请求,应用的响应时间就依赖于服务器的响应时间。这导致了用户界面的响应比本地应用慢得多。
什么是ajax
ajax的出现,刚好解决了传统方法的缺陷。AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
XMLHttpRequest 对象
XMLHttpRequest对象是ajax的基础,XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。目前所有浏览器都支持XMLHttpRequest
AJAX如何使用
完整的 AJAX 请求包括五个步骤:
创建 XMLHTTPRequest 对象
使用 open 方法创建 http 请求,并设置请求地址
设置发送的数据,用 send 发送请求
注册事件(给 ajax 设置事件)
获取响应并更新页面
function load() {
let xhhtp =new XMLHttpRequest();//创建一个xml对象
xhhtp.open('GET','ajax_info',true)//规定请求的类型,url文件在服务器上的位置,异步true同步false
xhhtp.setRequestHeader('Content-type','application/x-www-form-urlencoded')//规定请求头的名称和值
xhhtp.send();//把请求发送到服务器
/* 使用responseText 获得字符串的响应数据,使用responseXML响应XML数据
xml对象有三个重要属性,onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status状态两种
200: "OK"
404: 未找到页面 */
xhhtp.onreadystatechange=function(){
if(xhhtp.readyState==4&&xhhtp.status==200){
document.getElementById('demo').innerHTML=xhhtp.responseText;
}
}
}
// 这是调用下面函数的结构,这个结果大家应该很熟悉,就不解释了,应该都用过
myAjax({
type: "get",
url: "https://xxx",
data: { name: "沐华", age:18 },
dataType: "json",
async: true,
success:function(data){
console.log(data);
},
error:function(){
alert('报错');
}
})
// 定义一个将 { name: "沐华", age:18 } 转成 name=沐华&age=18 这种格式的方法
function fn(data){
let arr = []
for(let i in data){
arr.push( i+'='+data[i])
}
return arr.join('&')
}
// 下面就是实现上面调用和传参的函数
function myAjax(options){
let xhr = null
let str = fn(options.data)
// 创建 xhr
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject('Microsoft,XMLHTTP')
}
// 这里只配置了 get 和 post
if(options.type === 'get' && options.data !== undefined){
// 创建 http 请求
xhr.open(options.type, options.url+'?'+str, options.async || true)
// 发送请求
xhr.send(null)
}else if(options.type === 'post' && options.data !== undefined){
xhr.open(options.type, options.url, options.async || true)
// 设置请求头
xhr.setRequestHeaders('Content-type','application/x-www-form-urlencoede')
xhr.send(str)
}else{
xhr.open(options.type, options.url, options.async || true)
xhr.send(null)
}
// 监听状态
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
let res = xhr.responseText
try{
if(options.success === undefined){
return xhr.responseText
}else if(typeof res === 'object'){
options.success(res)
}else if(options.dataType === 'json'){
options.success(JSON.parse(res))
}else{
throw new Error()
}
}catch(e){
if(options.error !== undefined){
options.error()
throw new Error()
}else{
throw new Error()
}
}
}
}
}