ajax

ajax是一种技术方案,但并不是一种新技术。它依赖的是现有的CSS/HTML/Javascript,而其中最核心的依赖是浏览器提供的XMLHttpRequest对象,是这个对象使得浏览器可以发出HTTP请求与接收HTTP响应。 实现在页面不刷新的情况下和服务端进行数据交互。

作用:
传统的网页(不使用ajax)。如果需要更新内容,必须重新加载整个网页,而通过使用ajax可以在后台与服务器进行少量数据交换,可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

实现方式

  • XMLHttpRequest对象
  • fetch(兼容性不如XMLHttpRequest)
    兼容性查询

范例

GET 范例

//异步GET
var xhr = new XMLHttpRequest()
xhr.open('GET','/login?username=evenyao&password=123',true) //get类型 数据需要拼接成url放到?后面
xhr.send() console.log('readyState:',xhr.readyState)
xhr.addEventListener('readystatechange',function(){ //或者使用xhr.onload = function()
//查看readyState状态
console.log('readyState:',xhr.readyState)
})
xhr.addEventListener('load',function(){
console.log(xhr.status)
if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){
var data = xhr.responseText
console.log(data)
}else{
console.log('error')
}
})
xhr.onerror = function(){
console.log('error')
} //等同代码
var xhr = new XMLHttpRequest()
xhr.open('GET','/login?username=evenyao&password=123',true)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){
console.log(xhr.responseText)
}else{
console.log('error')
}
}
}
xhr.onerror = function(){
console.log('error')
}

POST 范例

//异步POST
var xhr = new XMLHttpRequest()
xhr.open('POST','/login',true) //post拼接数据放掉send里面
//post拼接数据放掉send里面
xhr.send(makeUrl({
username:'evenyao',
password:'123'
})) xhr.addEventListener('load',function(){
console.log(xhr.status)
if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){
var data = xhr.responseText
console.log(data)
}else{
console.log('error')
}
})
xhr.onerror = function(){
console.log('error')
} //makeUrl拼接函数
function makeUrl(obj){
var arr = []
for(var key in obj){
arr.push(key + '=' + obj[key])
}
return arr.join('&')
}

封装 ajax

//封装 ajax
function ajax(opts){
var url = opts.url
//如果有类型就使用用户输入的类型; 如果没有,默认为后面的
var type = opts.type || 'GET'
var dataType = opts.dataType || 'json'
var onsuccess = opts.onsuccess || function(){}
var onerror = opts.onerror || function(){}
var data = opts.data || {} //data序列化
var dataStr = []
for(var key in data){
dataStr.push(key + '=' + data[key])
}
dataStr = dataStr.join('&') //GET类型 使用url拼接
if(type === 'GET'){
url += '?' + dataStr
} //XMLHttpRequest对象创建
var xhr = new XMLHttpRequest()
xhr.open(type,url,true)
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//成功
//如果返回的数据类型是json,就解析成json格式
if(dataType === 'json'){
onsuccess(JSON.parse(xhr.responseText))
}else{
onsuccess(xhr.responseText)
}
}else{
onerror()
}
}
//如果断网,也会执行onerror()
xhr.onerror = onerror() //POST类型
if(type === 'POST'){
xhr.send(dataStr)
}else{
xhr.send()
}
} ajax({
url:'http://xxx',
type: 'POST',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
render(ret)
},
onerror: function(){
console.log('服务器异常')
showError()
}
}) function render(json){
} function showError(){
}

参考

你真的会使用XMLHttpRequest吗?
Ajax状态值及状态码

关于如何mock数据

http-server

本地使用http-server node工具启动一个静态服务器
以下是已经写好的ajax用法,这里采用GET类型,使用xhr.open('GET','/hello2.json',true)
在已经安装好nodehttp-server的情况下,先cd到对应的文件夹。然后通过http-server启动本地server。

 
 

通过访问127.0.0.1:8080/indexl.html,并进入控制台,即可看到mock结果

 

具体ajax用法代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
// ajax GET
var xhr = new XMLHttpRequest()
xhr.open('GET','/hello2.json',true)
xhr.send()
xhr.onload = function(){
console.log(xhr.status)
if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){
var data = xhr.responseText
console.log(data)
console.log(JSON.parse(data))
}else{
console.log('error')
}
}
xhr.onerror = function(){
console.log('error')
} </script>
</body>
</html>

模拟接口的json文件内容:

//hello2.json 内容
{
"name": "go",
"success": true,
"data": [
"70",
"80",
"90",
"年代"
]
}

github

在github上面写一个服务器进行mock
具体和本地区别不大,只是需要注意模拟接口的地址,因为域名是github.com,所以前面还需要加项目名,详情见github/mocktest里面的README.md
测试:
github pages

线上mock

使用easy-mock.com进行mock数据

  1. 进入easy-mock.com,登录注册账号之后进入创建项目,输入名称然后创建

     
     
  2. 进入创建好的项目
     
     
  3. 选择创建接口
     
  4. 填写类型(get/post)、描述、并输入JSON格式的内容,点击创建
     
     
  5. 生成链接,复制该链接
     
     
  6. 将该链接粘贴到之前写好的ajax用法的xhr.open('GET','',true)当中

     
     
     
    7.  打开页面,进入控制台查看mock结果

最新文章

  1. linux内核调试技术之自构proc
  2. Multiple dex files define Lcom/google/zxing/BarcodeFormat
  3. insmod过程详解【转】
  4. Retina视网膜屏中CSS3边框图片像素虚边的问题
  5. BizTalk动手实验(十二)WCF-Oracle适配器使用
  6. 2Sigma OA prepare: Longest Chain
  7. MySQL5.7.13源码编译安装指南(转)
  8. [vim]设置vim语法高亮显示和自动缩进
  9. WinCacheGrind配合XDebug分析PHP程序性能
  10. Robotium--scroll操作系列
  11. Android 4.4 Kitkat Phone工作流程浅析(六)__InCallActivity显示更新流程
  12. jQuery工具函数上
  13. CodeForces 706D Vasiliy&#39;s Multiset
  14. swift 启动图片的设置
  15. myeclipse 奔溃解决办法
  16. 01_Eclipse的使用方法
  17. Redis详解(三)------ redis的五大数据类型详细用法
  18. 异步与并行~CancellationTokenSource对线程的作用
  19. Python 读写文件 中文乱码 错误TypeError: write() argument must be str, not bytes+
  20. servlet编码问题

热门文章

  1. 课时53.video标签(掌握)
  2. Unity 游戏框架搭建 (二十一) 使用对象池时的一些细节
  3. JS中some(),every(),fiflter(),map()各种循环的区别理解
  4. 模板——最小生成树kruskal算法+并查集数据结构
  5. Struts2+Spring+Hibernate整合开发(Maven多模块搭建)
  6. SQL优化例子
  7. linux系统中用户
  8. tornado用户指引(四)------tornado协程使用和原理(三)
  9. Java核心技术36讲----------谈谈final、finally、finalize有什么不同
  10. 用树莓派3B+和 ITEAD PN532 读取、破解、写入M1卡