Javascript 没有可用缓存时的Ajax请求

Javascript 没有可用缓存时的Ajax请求,javascript,jquery,ajax,caching,Javascript,Jquery,Ajax,Caching,我是JavaScript/jQuery新手,我认为我的问题并不难解决 我想在会话中缓存一个变量(列表),如果之前没有缓存该列表,则应该发出ajax请求。 我的问题是,globalList在ajax请求之后为空,因此我认为我必须等待完成请求,但我不确定如何完成 var globalList; function initStuff() { globalList = JSON.parse(sessionStorage.getItem('globalList')); // if no c

我是JavaScript/jQuery新手,我认为我的问题并不难解决

我想在会话中缓存一个变量(列表),如果之前没有缓存该列表,则应该发出ajax请求。 我的问题是,
globalList
在ajax请求之后为空,因此我认为我必须等待完成请求,但我不确定如何完成

var globalList;
function initStuff() {
    globalList = JSON.parse(sessionStorage.getItem('globalList'));
    // if no cached variable is available, get it via ajax request
    if (!globalList) {
        $.getJSON('jsonGetStuff.htm', function (data) {
            sessionStorage.setItem('globalList', JSON.stringify(data));
            globalList = JSON.stringify(data);
        });
    }

    // null, if no cached value is available
    console.log("globalList=" + globalList);

    // TODO: process 'globalList'
}

如果您的url对于浏览器是唯一的,则不会缓存您的请求响应。众所周知,使用它就像“your.domain.com/some/uri?{timestamp}”一样

试试这个:

var globalList;
function initStuff() {
    globalList = JSON.parse(sessionStorage.getItem('globalList'));
    // if no cached variable is available, get it via ajax request
    if (!globalList) {
        $.getJSON('jsonGetStuff.htm?' + (new Date()).getTime(), function (data) {
            sessionStorage.setItem('globalList', JSON.stringify(data));
            globalList = JSON.stringify(data);
        });
    }

    // null, if no cached value is available
    console.log("globalList=" + globalList);

    // TODO: process 'globalList'
}
但是jquery也有cache:false特性(参考:):

但我喜欢像上面第一个例子那样做

或者更好:

$.ajax({
    cache: false,
    url: "jsonGetStuff.htm",
    method: "GET",
    dataType: "json",
    success: function(data) {
        sessionStorage.setItem('globalList', JSON.stringify(data));
        globalList = JSON.stringify(data);
    }
});

参考:

以下是示例代码:

var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});

您可以根据需要进行必要的更改。

如果您能详细说明,这个答案就可以了。
var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});