有什么方法可以模拟ajax请求?

问题描述

有什么方法可以模拟ajax请求?即页面刷新,但是数据自己定义不用从后台获取,最好可以封装成一个函数

阅读 4.1k
5 个回答

可以自定义一个json用ajax来调用,参数什么的可以根据需求来自己设定

mockjs是个不错的工具,拦截原生xmlhttprequest对象实现自定义模拟ajax返回数据,不侵入业务代码,结合webpack脚本,一套真实的ajax调用,一套本地模拟数据

用localStorage或者sessionStorage也可以,但不存储大量数据

使用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)
  })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题