问题描述
有什么方法可以模拟ajax请求?即页面刷新,但是数据自己定义不用从后台获取,最好可以封装成一个函数
mockjs是个不错的工具,拦截原生xmlhttprequest对象实现自定义模拟ajax返回数据,不侵入业务代码,结合webpack脚本,一套真实的ajax调用,一套本地模拟数据
使用Promise模拟吧, 需要的话可以配合localStorage做本地的数据持久化,这样刷新页面也不会丢失数据。
一个简单的例子:
const CLASS_LIST = [
{
id: '1',
title: '1班',
ceiiling: 100,
open: true,
autoNotify: true,
autoPush: false,
masterList: [{ id: 1, perm: 1}],
masterRatio: '',
teacherRatio: '99'
},
{
id: '2',
title: '2班',
ceiiling: 100,
open: true,
autoNotify: true,
autoPush: false,
masterList: [],
masterRatio: '',
teacherRatio: '99'
}
]
export function getClassList () {
return new Promise((resolve, reject) => {
resolve(CLASS_LIST.map(item => ({ id: item.id, title: item.title })))
})
}
export function addClass (title) {
let id = 0
for (let item of CLASS_LIST) {
if (+item.id >= id) id = String(1 + (+item.id))
}
let classItem = {
id,
title,
ceiiling: 100,
open: true,
autoNotify: true,
autoPush: false,
masterList: []
}
CLASS_LIST.push(classItem)
return new Promise((resolve, reject) => {
resolve(classItem.id)
})
}
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
可以自定义一个json用ajax来调用,参数什么的可以根据需求来自己设定