zoukankan      html  css  js  c++  java
  • 移动web开发ajax缓存操作

    移动web开发过程中网速是必须考虑的一个因素,所以一般是尽可能的在本地存储数据,避免弱网环境下请求数据失败导致页面没有内容的情况。

    前后端分离是web开发的必然趋势,在PC端我们有时甚至为了避免ajax缓存去做一些处理,但是移动端我们却需要把ajax请求给缓存下来,尤其是json数据。

    function ajaxCache(opt){
    function
    getStoreKey(opt){ var url = opt.url; //缓存最后面的json文件名 var storeKey = url.match(/([^/]*)/*$/)[1]; var hashStr = url; if (opt.data){ hashStr += JSON.stringify(opt.data); } var hash = hashStr; storeKey += hash; return storeKey; } //加载缓存的数据 function loadCachedData(opt, storage){ var storeKey = getStoreKey(opt); var data = storage.getItem(storeKey); try{ data = JSON.parse(data); } catch(e){ Logger.log(storeKey+":缓存数据解析出错"); data = null; } return data; } function attachSuccessProxy(opt, storage){ var oldSuccess = opt.success; opt.success = function(){ var data = arguments[0]; if (data){ var storeKey = getStoreKey(opt); storage.setItem(storeKey, JSON.stringify(data)); } oldSuccess.apply(this, arguments); }; } var cachedAjax = function(opt){ if (!opt.url){ opt.url = location.toString(); } if (opt.sessionCache && opt.success){ var sessionData = loadCachedData(opt, session); if (sessionData){ opt.success(sessionData, 'session'); return; // no further request from remote server } attachSuccessProxy(opt, session); } if (opt.localCache && opt.success){ var localData = loadCachedData(opt, local); if (localData){ opt.success(localData, 'local'); } attachSuccessProxy(opt, local); } $.ajax(opt); }; return cachedAjax;
    }
  • 相关阅读:
    Django框架-模板层
    Django框架-路由层
    Django流程-以登录功能为例
    常见的MySQL慢查询优化
    函数之二
    python 之 函数
    python 文件操作
    set dict tuple 内置方法
    leetcode
    python 之 数据类型初接触
  • 原文地址:https://www.cnblogs.com/hutuzhu/p/4318254.html
Copyright © 2011-2022 走看看