Ajax全称:
Async Javascript and XML,翻译后就是异步的JavaScript 和XML,可以在不重选加载页面的情况下,与服务器交换数据,并实现部分页面更新。
Ajax原理:
通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用JavaScript来操作DOM而更新页面。
Ajax实现过程:
1.新建 一个 XmlHttpRequest 实例化对象;
复制代码
1const xhr = new XmlHttpRequest();
2.通过 XmlHttpRequest 对象的open()方法连接服务器;
复制代码
1xhr.open(method,url,[async]...)
3.通过 XmlHttpRequest 对象的send()方法传递数据至服务器;
复制代码
1xhr.send([body])
4.通过 XMLHttpRequest 对象提供的 onreadystatechange 事件监听服务器通信状态;
readyState五个状态:
- 0 —— 未连接
- 1 —— 已打开
- 2 —— 已获取响应头
- 3 —— 正在下载
- 4 —— 传输结束
5.根据服务器返回的状态及数据,处理更新页面。
Ajax封装:
复制代码
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
31function ajax(options){ // 创建xhr实例 const xhr = new XMLHttpRequest(); //初始化参数内容 options = options || {} ; options.type = (options.type || '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){ if(xhr.status>=200 && xhr.status<300){ options.success && options.success(xhr.responseText,xhr.responseXML); }else{ options.fail && options.fail(status) } } } }
Ajax使用:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12ajax({ type:'get/post', dataType:'json', url:'', data:'', success:function(text){ console.log(text) }, fail: function(status){ console.log(status) } })
最后
以上就是还单身哈密瓜最近收集整理的关于面试题二十:Ajax 原理是什么?ajax 是如何实现的?的全部内容,更多相关面试题二十:Ajax内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复