Having problem with a callback method for this jQuery getJSON AJAX call
i've got a utility .js file that grabs some data via Ajax. Now this utility method doesn't know who will call it.
So when the Ajax async completes, it needs to send an object back to the caller. I'm not sure how to do this :(
This is the code I have...
function someMethod(a, b, c) {
// ... stuff ...
// Now fire it off, asynchronously!
var request = $.getJSON(url, function (jsonResult) {
var result =
{
json: jsonResult,
contentLength: request.getResponseHeader("Cont开发者_如何学Cent-Length")
};
// TODO: Now return this result to the caller.
});
}
of course, i can't use return result;
because this is async. I feel like i need to pass in a parameter that is the function which the ajax code above needs to call, when the result has been async finished. Just not sure how .. because remember .. this is method has no idea who is calling it .. so it doesn't know about any other methods and stuff.
Any ideas, please?
You are right. You will need to pass in the function to "someMethod" so that you can return the data to it. Depending on what the callback function does you might also need to set it's context properly by using the call or apply methods. The "context" is what what the "this" keyword will be set to in the callback function.
If your callback function doesn't make any references to the keyword "this" then you can ignore the use of call() or apply() and just call the function as in the second example. (e.g. callback(result));
function someMethod(a, b, c, callback, context) {
// ... stuff ...
// Now fire it off, asynchronously!
var request = $.getJSON(url, function (jsonResult) {
var result =
{
json: jsonResult,
contentLength: request.getResponseHeader("Content-Length")
};
// Now return this result to the caller. With the context set
callback.call(context, result);
// Example of callback without setting the context
//callback(result);
});
}
精彩评论