简体   繁体   中英

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

If it's in localStorage, this works:

console.log(this.getJSON(url))

If it's not and it's returning the AJAX object:

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?

You could add a callback parameter to your getJSON method like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM