jQuery will not set a higher scoped object in callback
I have a jQuery c开发者_运维知识库allback function. In that function I want it to change the value of a variable that is in a higher scope, but for some reason it is not doing that. Here is the code:
function add() {
var returnedData = {
my_id: 0
};
$.post("add_event.php", { event : toSendText }, function(data) {
returnedData.my_id = 5;
}, "json");
if(add_page == true){
alert(returnedData.my_id);
window.open('content-list.php?cal_id=');
}
}
The problem is that $.post()
is asynchronous, so that returnedData.my_id = 5;
happens after your alert()
does (the data comes back from the server at some point later, when the request finishes).
To make this work like you want, you need to continue working in the callback once your data is available, like this:
function add() {
$.post("add_event.php", { event : toSendText }, function(data) {
if(data.add_page == true) {
//use data in some way here presumably
window.open('content-list.php?cal_id=' + data.id); //maybe this?
}
}, "json");
}
jQuery.ajax( settings )
async Boolean Default: true
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
http://api.jquery.com/jQuery.ajax/
The jQuery.post( settings )
by default doesn't pass the parameter async
so it assumes true
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
http://api.jquery.com/jQuery.post/
精彩评论