返回ajax数据[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
                            <span class="question-originals-answer-count">
                                (38 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-04-14 22:49:37Z" class="relativetime">5 years ago</span>.</div>
        </div>
    </aside>

I have an ajax call in a function and I did not find a solution how to return the data:

function get_blog_post(id){

    var info="id="+id;
    $.ajax({
            type: 'POST',
            url: 'get_blog_post.php',
            data: info,
            success: function(data){
                return data;
            }
    });

}

The code above doesn't works. The data contains the right answer but I can't use it if I callthe get_blog_post() function.

:\

</div>

The success function runs some time after the ajax call completes. That's the nature of asynchronous calls--like ajax in javascript.

That means you cant return it and have to do something with the data in that function. Perhaps it is text and you put it into a text area like:

success: function(data){
             $('textarea').val(data);
         }
function get_blog_post(id, callback){

    var info="id="+id;
    $.ajax({
        type: 'POST',
        url: 'get_blog_post.php',
        data: info,
        success: function(data){
            callback(data);
        }
    });
}

get_blog_post(5, function(data){
    // use data here
});

OR set async = false (not recommended):

    $.ajax({
        type: 'POST',
        url: 'get_blog_post.php',
        data: info,
        async: false,
        success: function(data){
            return data;
        }
    });

Provide a callback method and do what ever you want to do inside it

function get_blog_post(id, callback){

    var info="id="+id;
    $.ajax({
            type: 'POST',
            url: 'get_blog_post.php',
            data: info,
            success: callback
    });

}