[英]Ajax request if no cache is available
I'm new to JavaScript/jQuery and I think my problem isn't that hard to solve. 我是JavaScript / jQuery的新手,我认为我的问题并不难解决。
I want to cache a variable (list) in a session and if that list wasn't cached before, an ajax request should be made. 我想在会话中缓存一个变量(列表),如果以前没有缓存过该列表,则应该发出一个ajax请求。 My Problem is that
globalList
is null after the ajax request, so I think I've to wait for finishing the request but I'm not sure how to do this. 我的问题是ajax请求之后
globalList
为null,所以我认为我必须等待完成请求,但是我不确定如何执行此操作。
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'
}
Your response of request will not be cached when Your url is unique for browser. 当您的网址对于浏览器而言是唯一的时,您的请求响应将不会被缓存。 It's well know practice use it like "your.domain.com/some/uri?{timestamp}".
众所周知,实践会像“ your.domain.com/some/uri?{timestamp}”那样使用它。
Try this: 尝试这个:
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'
}
but also jquery has cache: false feature (reference: http://www.w3schools.com/jquery/ajax_ajaxsetup.asp ) : 而且jquery具有cache:false功能(参考: http : //www.w3schools.com/jquery/ajax_ajaxsetup.asp ):
$(function() {
$.ajaxSetup({ cache: false });
});
but I'm fan of doign it like in first example above. 但我喜欢上面第一个示例中的主题。
or some better: 或更好的:
$.ajax({
cache: false,
url: "jsonGetStuff.htm",
method: "GET",
dataType: "json",
success: function(data) {
sessionStorage.setItem('globalList', JSON.stringify(data));
globalList = JSON.stringify(data);
}
});
reference: http://api.jquery.com/jquery.ajax/ 参考: http : //api.jquery.com/jquery.ajax/
Here is the example code for you: 这是适合您的示例代码:
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" );
});
You can make required changes based on your need. 您可以根据需要进行必要的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.