function getData(d){
Back = new Object();
$.getJSON('../do.php?',
function(response){
if(response.type == 'success'){
Back = { "type" : "success", "content" : "" };
$.each(response.data, function(data){
Back.content +='<div class="article"><h5>'+data.title+'</h5>'
Back.content +='<div class="article-content">'+data.content+'</div></div>';
});
}
else{
Back = {"type" : "error" };
}
return Back;
});
}
console.log(getData());
is returning undefined! why?
You can’t call an asynchronous function in a synchronous way. In your code, this:
Runs after this:
console.log(getData());The callback (second parameter) in
$.getJSONruns once the server returns a response, this doesn’t happen instantly.If you call the logging when it actually runs like this, you will get the expected results: