分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

ajax 和 mock 数据

发布时间:2023-09-06 02:07责任编辑:蔡小小关键词:暂无标签

ajax

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

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

实现方式

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

范例

GET 范例

//异步GETvar 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 范例

//异步POSTvar 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

//封装 ajaxfunction 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结果

ajax 和 mock 数据

原文地址:https://www.cnblogs.com/evenyao/p/9404656.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved