No; $.post
executes asynchronously, so when you call console.log
, the AJAX request is still running and hasn't yet yielded a response. This is the purpose of the callback function: to provide code to be run after the request has completed. If you move console.log
into the callback function, it should work:
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
var response = data_response; //I need to access this variable outside of $.post()
console.log(response);
}
}, "json");
Update: If you want the response data to be globally available, you can declare the variable in the global scope like so:
var response = null;
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
response = data_response;
console.log(response);
}
}, "json");
Of course, the only context in which you can be sure that response
has
actually been populated with a value is in the callback function supplied to
$.post
after the line response = data_response;
. If you want to use it at
any other stage in the script then you'll have to check its value first;
something like this:
if (response !== null)
{
console.log(response);
}
Just be aware that this code won't do anything if you put it straight after
the $.post
call; it'll only be useful if it's executed after the POST request has finished, in some other asynchronous callback (perhaps a UI interaction event of some kind).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…