Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用下面的jquery ajax缓存代码时,jquery ajax中的回调不起作用_Javascript_Jquery_Ajax_Callback - Fatal编程技术网

Javascript 使用下面的jquery ajax缓存代码时,jquery ajax中的回调不起作用

Javascript 使用下面的jquery ajax缓存代码时,jquery ajax中的回调不起作用,javascript,jquery,ajax,callback,Javascript,Jquery,Ajax,Callback,下面是我的代码,问题是如果任何ajax调用成功回调,缓存代码工作不正常 var localCache = { /** * timeout for cache in millis * @type {number} */ timeout: 30000, /** * @type {{_: number, data: {}}} **/ data: {}, remove: function (url) {

下面是我的代码,问题是如果任何ajax调用成功回调,缓存代码工作不正常

var localCache = {
    /**
     * timeout for cache in millis
     * @type {number}
     */
    timeout: 30000,
    /** 
     * @type {{_: number, data: {}}}
     **/
    data: {},
    remove: function (url) {
        delete localCache.data[url];
    },
    exist: function (url) {
        return !!localCache.data[url] && ((new Date().getTime() - localCache.data[url]._) < localCache.timeout);
    },
    get: function (url) {
        console.log('Getting in cache for url' + url);
        return localCache.data[url].data;
    },
    set: function (url, cachedData, callback) {
        localCache.remove(url);
        localCache.data[url] = {
            _: new Date().getTime(),
            data: cachedData
        };
        if ($.isFunction(callback)) callback(cachedData);
    }
};

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (options.cache) {
        var complete = originalOptions.complete || $.noop,
            url = originalOptions.url;
        //remove jQuery cache as we have our own localCache
        options.cache = false;
        options.beforeSend = function () {
            if (localCache.exist(url)) {
                complete(localCache.get(url));
                return false;
            }
            return true;
        };
        options.complete = function (data, textStatus) {
            localCache.set(url, data, complete);
        };
    }
});

function handleAjaxRequests(url, parameters, headers, method, successHandler, options, errorHandler) {

        if (typeof (method) === 'undefined') {
            method = "GET";
        }
        if (typeof (headers) === 'undefined') {
            headers = "";
        }
        if (typeof (parameters) === 'undefined') {
            parameters = "";
        }
        successHandler = typeof (successHandler) === 'undefined' ? function (data) {} : successHandler;
        errorHandler = typeof (errorHandler) === 'undefined' ? function (data) {} : errorHandler;
        return $.ajax({
            method: method.toUpperCase(),
            url: url,
//            async: false,
            data: parameters,
            headers: headers,
            success: function (data) {
                console.log('hi');
                successHandler(data, options);
                console.log('bye');
            },
            error: function (data) {
                $('.loader').hide();
                errorHandler(data);
            },
        });
    }
var localCache={
/**
*缓存超时(毫秒)
*@type{number}
*/
超时:30000,
/** 
*@type{{}:编号,数据:{}
**/
数据:{},
删除:函数(url){
删除localCache.data[url];
},
存在:函数(url){
return!!localCache.data[url]&((new Date().getTime()-localCache.data[url]。)
成功运行ajax
successHandler(数据、选项)后按上述代码执行函数应该是触发器,但不是因为上面的缓存处理程序代码。我不知道这为什么不起作用。如果我写一些简单的东西,而不是回调函数,它就可以工作了。datatable Ajax回调也存在同样的问题。
在我的项目中,我必须在全局级别使用上述缓存处理程序,不管ajax请求来自datatable还是任何其他源


上面的缓存代码来自此处

正如聊天室中所讨论的,我对您的代码做了一些更改:

var localCache = {
  /**
   * timeout for cache in millis
   * @type {number}
   */
  timeout: 30000,
  /** 
   * @type {{_: number, data: {}}}
   **/
  data: {},
  remove: function(url) {
    delete localCache.data[url];
  },
  exist: function(url) {
    return !!localCache.data[url] && ((new Date().getTime() - localCache.data[url]._) < localCache.timeout);
  },
  get: function(url) {
    console.log('Getting in cache for url ' + url);
    return localCache.data[url].data;
  },
  set: function(url, cachedData, callback) {
    localCache.remove(url);
    localCache.data[url] = {
      _: new Date().getTime(),
      data: cachedData
    };
    console.debug('caching data for '+url, cachedData);
    if ($.isFunction(callback)) callback(cachedData);
  }
};

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  if (options.cache) {
    var complete = originalOptions.complete || $.noop,
      url = originalOptions.url;
    //remove jQuery cache as we have our own localCache
    options.cache = false;
    options.beforeSend = function() {
      if (localCache.exist(url)) {
        console.log('using cache, NO QUERY');
        complete(localCache.get(url));
        return false;
      }
      console.log('sending query');
      return true;
    };
    options.complete = function(data, textStatus) {
      localCache.set(url, data, complete);
    };
  }
});

function handleAjaxRequests(url, parameters, headers, method, successHandler, options, errorHandler) {
  method = method || "GET";
  headers = headers || {};
  parameters = parameters || {};

  return $.ajax({
    method: method.toUpperCase(),
    url: url,
    cache: true,
    //            async: false,
    data: parameters,
    headers: headers,
    success: successHandler,
    error: errorHandler,
  });
}

handleAjaxRequests('/echo/json/', {p1: 'hey'}, null, 'POST', function(data){console.log('first success without cache', data);});

setTimeout(function(){
handleAjaxRequests('/echo/json/', {p1: 'hey'}, null, 'POST', function(data){console.log('success! with cache hopefully', data);});
}, 2000);
您可以使用这个众所周知的javascript技巧来定义函数的范围


编辑2:如果希望
successHandler
即使在从缓存获取时也能运行,则应使用
complete
而不是
success

function handleAjaxRequests(url, parameters, headers, method, successHandler, options, errorHandler) {
  method = method || "GET";
  headers = headers || {};
  parameters = parameters || {};

  return $.ajax({
    method: method.toUpperCase(),
    url: url,
    cache: true,
    //            async: false,
    data: parameters,
    headers: headers,
    complete: (function(handler, opt) {
      return function( /*Anything*/ data, /*String*/ textStatus, /*jqXHR*/ jqXHR) {
        console.log('hi');
        handler(data, opt);
        console.log('bye');
      };
    })(successHandler, options),
    error: (function(handler, opt) {
      return function( /*jqXHR*/ jqXHR, /*String*/ textStatus, /*String*/ errorThrown) {
        console.log('ouch');
        handler(errorThrown);
      };
    })(errorHandler, options),
  });
}

.

是否正在打印?@82t在请求未缓存时打印。请求缓存后,它不会打印hi。您还可以告诉我们您是如何调用
handleAjaxRequests(…)
?另外,您也可以在AJAX错误处理程序中输入调试语句吗?这只是一个函数,我们为它传递参数,如
handleAjaxRequests(url、参数、头、方法、successHandler、选项、errorHandler)
this调用
handleAjaxRequests
时,您是否检查了参数?
function handleAjaxRequests(url, parameters, headers, method, successHandler, options, errorHandler) {
  method = method || "GET";
  headers = headers || {};
  parameters = parameters || {};

  return $.ajax({
    method: method.toUpperCase(),
    url: url,
    cache: true,
    //            async: false,
    data: parameters,
    headers: headers,
    complete: (function(handler, opt) {
      return function( /*Anything*/ data, /*String*/ textStatus, /*jqXHR*/ jqXHR) {
        console.log('hi');
        handler(data, opt);
        console.log('bye');
      };
    })(successHandler, options),
    error: (function(handler, opt) {
      return function( /*jqXHR*/ jqXHR, /*String*/ textStatus, /*String*/ errorThrown) {
        console.log('ouch');
        handler(errorThrown);
      };
    })(errorHandler, options),
  });
}