gpt4 book ai didi

javascript - 如果localStorage中存在数据,如何返回它,或者以其他方式执行AJAX请求?

转载 作者:行者123 更新时间:2023-11-29 19:36:02 25 4
gpt4 key购买 nike

抱歉措辞不当。这是代码

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

获取数据的两种方式:

如果它在 localStorage 中,这有效:

console.log(this.getJSON(url))

如果不是,则返回 AJAX 对象:

this.getJSON(url).done(function (result) {
console.log(result);
})

如何重新格式化,以便我可以获取数据而无需预料它是否在 localStorage 中?

最佳答案

您可以像这样向您的 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);
});
}

}

然后你可以调用

getJSON(function(json) {
// Do something with json
});

关于javascript - 如果localStorage中存在数据,如何返回它,或者以其他方式执行AJAX请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25026091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com