简体   繁体   中英

Setting a variable from ajax call

Let's get to the point. This is what I want to do: I have a bunch of userdata which I get from the server. I want to cache the data to avoid making requests to the server every time I need, say, the email or user's name.

So, I'd build functions such as getEmail, getUsername, and so on, which make the Ajax call once and save it in an object. If the function is called again, it will return the cached object.

The app is divided in modules. App contains the data. Here is the fiddle: http://jsfiddle.net/Osoascam/Nk6aw/

(open the console to see results)

Of course doing something like this:

var email = Module.Utilities.getEmail();

is wrong, as getEmail will call an Ajax function and thus email will remain undefined, even after the call is done. (I put that in the Fiddle to show what I'm trying to achieve). However, I can't set the variable inside getEmail() function or the one that calls Ajax, as several scripts must be able to call that function and set their variables accordingly.

What's the best way to do that? Make functions which retrieve a portion of an object return by an Ajax call in such a way that the call is made just once...

Thanks in advance,

Óscar

Ajax request is by default asynchronous. So, getEmail() should accept a callback parameter...

Module.Utilities.getEmail = function(next) {
  $.get('/api/getEmail/', function(res) {
    next(res);
  });
};

// when calling the function
Module.Utilities.getEmail(function(email) {
  console.log(email);
});

That said, you could also look into synchronous ajax request ...

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