在ajax中使用函数外部的变量

How can i use a variable in a function outside the function. The console.log(response) shows that the content is been fetch from the php. The alert(lng) shows undefined. Why? What could be the issue with this script.I have been on it for a while.

below is the script.

    var lat;
    var lng ;
    $.ajax({
            type: 'GET',
            url: 'getlocation.php',
            data: 'param=no' ,
            dataType: 'JSON',
            success: function (response) {
                console.log(response);
                lat = response.latitude;
                lng = response.latitude;
            },
            error: function (response){
                alert (response);
            }

        });
    alert( lng);

Because the variable lng is not set when the code runs to the line alert(lng).

The Ajax call is async. That means, JS engine goes into the flow:

  1. Issue http request ($.ajax...)

(At this point, since the network operation is slow, so JS engine chooses to continue executing the following lines. It comes back after the response completes.)

  1. Runs into line alert(lng). At this point, it is still undefined.
  2. The request responses success/error, then run corresponding callback function function(response).... Alert inside the callback function will get what you want.