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

问题描述

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

已解决 悬赏分:50 - 解决时间 2021-11-27 22:04
反对 0举报 0 收藏 0

回答5

最佳
  • @

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

    支持 0 反对 0 举报
    2021-11-27 01:40
  • @

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

    支持 0 反对 0 举报
    2021-11-27 02:48
  • @

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

    支持 0 反对 0 举报
    2021-11-27 03:34
  • @

    使用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)
      })
    }
    支持 0 反对 0 举报
    2021-11-27 04:37
  • @

    Service_Workers

    Demo https://pwa-note.github.io/

    支持 0 反对 0 举报
    2021-11-27 05:09