[英]if data exists in localStorage, how to return it, or otherwise perform AJAX request?
Sorry for poor wording. 对不起,措辞不好。 Here's the code 这是代码
getJSON : function(url) {
if ( localStorage.getItem(url) ) {
console.log('Getting from localStorage instead');
return $.parseJSON(localStorage.getItem(url));
} else {
console.log('No results locally, making XHR request...');
return $.ajax({
url: 'curl.php',
type: 'GET',
data: {
url : url
}
}).done(function (result) {
var json = $.parseJSON(result);
console.log('Setting to localStorage with key:', url);
localStorage.setItem(url, result);
})
}
}
Two ways of getting the data: 两种获取数据的方式:
If it's in localStorage, this works: 如果在localStorage中,则可以使用:
console.log(this.getJSON(url))
If it's not and it's returning the AJAX object: 如果不是,它将返回AJAX对象:
this.getJSON(url).done(function (result) {
console.log(result);
})
How can this be reformatted so that I can get the data without anticipating of if it's in localStorage or not? 如何重新格式化它,以便我可以在不预料是否在localStorage中的情况下获取数据?
You could add a callback parameter to your getJSON
method like so: 您可以将回调参数添加到getJSON
方法中,如下所示:
this.getJSON = function(callback)
{
if ( localStorage.getItem(url) ) {
console.log('Getting from localStorage instead');
// If it's in local storage execute callback immediately
callback($.parseJSON(localStorage.getItem(url)));
} else {
console.log('No results locally, making XHR request...');
$.ajax({
url: 'curl.php',
type: 'GET',
data: {
url : url
}
}).done(function (result) {
var json = $.parseJSON(result);
console.log('Setting to localStorage with key:', url);
localStorage.setItem(url, result);
callback(json);
});
}
}
You could then call 然后你可以打电话
getJSON(function(json) {
// Do something with json
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.