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结果

ajax 和 mock 数据的更多相关文章

  1. 前端通信:ajax设计方案(十)--- 完善Promise A+规范,增加mock数据功能

    半年不迭代,迭代搞半年,说的就是我,这里有点尴尬了,直接进入主题吧 我记得在这篇博客的时候集成了Promise的,不过那个时候就简简单单的写了一点最基础,在一些特殊的case上,还是有点问题的,所以才 ...

  2. vue-cli项目中怎么mock数据

    在vue项目中, mock数据可以使用 node 的 express模块搭建服务 1. 在根目录下创建 test 目录, 用来存放模拟的 json 数据, 在 test 目录下创建模拟的数据 data ...

  3. json-server mock数据

    前言: 项目开发中,影响项目进程的常常是由于在前后端数据交互的开发流程中停滞,前端完成静态页面的开发后,后端迟迟未给到接口.而现在,我们就可以通过根据后端接口字段,建立一个REST风格的API接口,进 ...

  4. vue-cli项目使用mock数据的方法(借助express)

    前言 现如今前后端分离开发越来越普遍,前端人员写好页面后可以自己模拟一些数据进行代码测试,这样就不必等后端接口,提高了我们开发效率.今天就来分析下前端常用的mock数据的方式是如何实现的. 主体 项目 ...

  5. 使用node.js + json-server + mock.js 搭建本地开发mock数据服务

    在开发过程中,前后端不论是否分离,接口多半是滞后于页面开发的.所以建立一个REST风格的API接口,给前端页面提供虚拟的数据,是非常有必要的.对比过多种mock工具后,我最终选择了使用 json se ...

  6. mock数据(模拟后台数据)

    mock数据(模拟后台数据) - Emily恩 - 博客园 https://www.cnblogs.com/enboke/p/vue.html Mock.js http://mockjs.com/ 前 ...

  7. Electron-vue实战(二)— 请求Mock数据渲染页面

    Electron-vue实战(二)— 请求Mock数据渲染页面 作者:狐狸家的鱼 本文链接 GitHub:sueRimn 一.环境搭建 1.安装Mock.js 如果仅仅用作脱离后台的模拟数据,就安装在 ...

  8. mock 数据 解决方案

    前端工程化之--Mock解决方案   https://www.jianshu.com/p/720b12b5d120 一.为什么要使用mock数据: 1.后端接口数据没有的时候,前端根据接口文档,使用 ...

  9. vue mock数据(模拟后台)

    本文转载自:https://blog.csdn.net/benben513624/article/details/78562529 vue实现ajax获取后台数据是通过vue-resource,首先通 ...

随机推荐

  1. 流Stream 文件File 流IO

    Java 流(Stream).文件(File)和IO Java.io 包几乎包含了所有操作输入.输出需要的类.所有这些流类代表了输入源和输出目标. Java.io 包中的流支持很多种格式,比如:基本类 ...

  2. 用javascript编写简单银行取钱存钱流程(函数)

    const readline = require('readline-sync')//引用readline-sync let arr = [[], []]; //登陆 let add = functi ...

  3. windows安装的mysql中文乱码的坑

    本机装的mysql为5.6的,从代码执行的中文inert语句总是显示问号,然后在中文查询是都会报问题 今天终于解决了! 问题解决方法为: 找到my.ini文件在文件中加入 [client]defaul ...

  4. Knowledge Point 20180308 拔下forEach的外衣

    剖析加强for 很长一段时间对于foreach都有一种误解,那就是foreach只是普通for的包装,底层还是普通for循环,直到深入了解迭代器的时候,才发现自己错了,本节就来探讨一下foreach, ...

  5. RabbitMQ初学之踩坑记录

    1:账号或密码错误 com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused usi ...

  6. springsource-tool-suite插件下载

    下载地址:    https://spring.io/tools3/sts/all/ 下载页面上的 update sites archives文件

  7. markdown常用命令(持续整理更新...)

    编写使用的工具 VS Code 拥有丰富插件支持的代码编辑器,当然也支持markdown MdEditor一款在线编辑markdown网站 1.标题 示例: # 一级标题 ## 二级标题 ### 三级 ...

  8. h5跳转到app的实现

    随着业务的增加,可能存在这么一种需求,就是需要从h5中直接跳转到app.如果没有安装app的话,则提示到应用市场或者app store下载安装.不过问题就在这个地方,单纯的用h5是没有方法判断是否安装 ...

  9. PHP在foreach中对$value赋值

    foreach ($data as $key => $value) { $data[$key]['name'] = '测试在value中赋值';}

  10. IDEA阿里Java规范插件的安装

    本文参考自阿飞博客:http://www.cnblogs.com/aflyun/p/7668306.html 官方使用教程:https://zhuanlan.zhihu.com/p/30191998? ...