2015-05-29 54 views
1

我是JavaScript/jQuery的新手,我认为我的问题并不难解决。Ajax请求如果没有缓存可用

我想在会话中缓存一个变量(列表),并且如果该列表之前没有被缓存,应该发出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' 
} 

回答

1

当您的网址对浏览器唯一时,您的请求响应将不会被缓存。这是众所周知的实践使用它,如“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有缓存:伪特征(参考:http://www.w3schools.com/jquery/ajax_ajaxsetup.asp):

$(function() { 
    $.ajaxSetup({ cache: false }); 
}); 

但我doign它像上面第一个例子的风扇。

或一些更好:

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

参考:http://api.jquery.com/jquery.ajax/

+0

这个答案会很好,如果你能详细说明。 – Girish

+0

完成(: 可以查看吗? – num8er

0

下面是示例代码为您提供:

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"); 
}); 

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