简体   繁体   中英

using a variable outside a function in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM