jQuery callback with parameters
I'm trying to call a function, then take the returned variable and display it on the screen within a div. However, in my current format below, the .html() gets executed simultaneously as the postGameStatistics(开发者_如何学JAVA) function. postGameStatistics() is a function that does an ajax post amongst some other actions. Is there a way to chain this?
var fbDiv = "#fb-request-wrapper";
var xp = postGameStatistics(fbDiv, "#loading_fb", "p2", null);
$(fbDiv).html("Congrats! you've just earned " + xp + " XPs.");
$(fbDiv).show();
Two options. I think the second one is really what you want.
1) set the optional "async" property of a jQuery ajax request to false. This will make the rest of the script wait until the request has finished before proceeding. For example:
$.ajax({
url: http://example.com,
type: 'POST',
async: false,
data: myData,
success: function(data){
//handle a successful request
},
error: function(data){
//handle a failed request
}
});
2) Execute the second two lines of code in the "success" callback of the $.ajax method. This is the standard jQuery way to handle AJAX requests. Note that you do not need to set async to false in this case:
$.ajax({
url: http://example.com,
type: 'POST',
data: myData,
success: function(data){
$(fbDiv).html("Congrats! you've just earned " + data + " XPs.");
$(fbDiv).show();
},
error: function(data){
//handle a failed request
}
});
You could move the $(fbDiv).html()
and $(fbDiv).show()
into a callback function, that get`s called after the ajax request finished successful.
So your request would look something like:
var postGameStatistics = function(div) {
var $div = $(div);
$.get('get/xp', {some: "parameters"}, function(response) {
var xp = response.xp;
$div.html("Congrats! you've just earned " + xp + " XPs.");
$div.show();
});
};
with jQuery your can use ajax() function to make ajax calls. To achieve what you want, consider using success() or cemplete() methods under ajax() function. In success() method you can fill and show your DIV element.
More can be read here: http://api.jquery.com/jQuery.ajax/
EDIT.
A little example
$.ajax({
url: 'http://example.com/something',
action: 'post',
success: function( data ) {
$(fbDiv).html("Congrats! you've just earned " + xp + " XPs.");
$(fbDiv).show();
}
});
精彩评论