AJAX请求变量问题[重复]

This question already has answers here:
                </div>
            </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2013-01-10 17:30:11Z" class="relativetime">7 years ago</span>.</div>
        </div>
    </aside>

Possible Duplicate:
jQuery global variable problem

I'm doing a jQuery AJAX call and I want to save into a variable the response. However this variable is not having the value of the response outside of the AJAX call function. How can I get the response outside of the AJAX call function?

Example:

var responseText = '';
$.ajax({
    url: 'clients_handler.php',
    type: 'post',
    data: { action: 'check_email', email: email },
    success: function(data) {
        responseText = jQuery.parseJSON(data);
    }
});
console.log(responseText);

So from my example responseText will be empty as set before the AJAX function. How can i set this variable with the AJAX response value?

</div>

You cannot save your variable the way you want because it is within a closure. The best you can do is to pass the response data to a function that will be executed after the request is done. Here's an example:

//code
$.ajax({
    url: 'clients_handler.php',
    type: 'post',
    data: { action: 'check_email', email: email },
    success: function(data) {
        responseHandler(data);
    }
});


function responseHandler(data){
    console.log(data);
}

The simple answer is that ajax fires asynchronously. Essentially this means that you don't know when the ajax code will complete, so any lines of code after the call to $.ajax may execute before the $.ajax finishes (but not necessarily). This is why callbacks for ajax are necessary.

One solution is to make the ajax request synchronous by using the jQuery.ajax option async: false, but this is probably not desired.

The true solution is to use the callbacks appropriately -- do all work you need to with responseText within the success: function.

Don't like having all of that code in one spot? jQuery was nice enough to create Deferred and have jqxhr implement it:

var jqxhr = $.ajax({url: url, data: data});
//thousands of lines of code here
$.when(jqxhr).done(function (responseText) { console.log(responseText); });