How do you write a function that returns a value fetched from server via $.get
?
This is what I have tried, which does not work:
function getMessage(key) {
$.get("/messages.json", function(data) {
return data.me开发者_如何学Gossages[key];
}, "json");
}
Any ideas?
Because Ajax requests are asynchronous. That is why you have to pass a callback to $.get
, to handle the data once it is available. But the getMessage
function returns before the $.get
callback is executed.
You have to pass a callback that is doing something with the return value. E.g.:
function getMessage(key, cb) {
$.get("/messages.json", function(data) {
cb(data.messages[key]);
}, "json");
}
getMessage('foo', function(data) {
alert(data);
});
Of course you can also pass the callack directly to $.get
and handle the data extraction there:
function getMessage(cb) {
$.get("/messages.json", cb);
}
There are two ways to handle this: use a synchronmous call via $.ajax
or pass in a callback to your function instead of having it return a value. The latter is the canonical way to deal with AJAX since it retains the asynchronous nature of the call.
Asynchronous
function processMessage(key,elem,cb) {
$.get('/messages.json', function(data) {
if (cb && typeof(cb) === 'function') {
cb.apply(elem,data.messages[key]);
}
}
}
$('.something').each( function() {
processMessage('somekey', this, function(msg) {
$(this).append(msg);
});
});
Synchronous - try not to do it this way, since you'll lock your browser until it's done.
function getMessage(key)
{
var result = '';
$.ajax({
url: '/messages.json',
aSync: false,
type: 'get',
dataType: 'json',
success: function(data) {
result = data.messages[key];
}
});
return result;
}
$('.something').each( function() {
var msg = getMessage('somekey');
$(this).append(msg);
});
Note: these are untested.
精彩评论