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结果
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程