简体   繁体   中英

Callback with javascript and jquery

I am more of a java developer and am having difficulty with javascript callback. I am wondering if any experts here would help me out of my struggle with this code.

I am trying to pull our locations from db and populating in an array. On first load i am trying to refresh all locations and I am having trouble to control the flow of execution and loading values. Below is the code and I have put in the output at the end.

JQUERY CODE:

         // load all locations on first load.
            refreshLocations();
            $("#locInput").autocomplete({source: locationData});
             }); // end of document.ready

            // function to refresh all locations.
             function refreshLocations() {
                 getLocationArray(function(){
                     console.log("firing after getting location array");
                  });
              }
            // function to get the required array of locations.
            function getLocationArray() {
               getJsonValues("GET", "getLocalityData.php", "", getLocalityFromJson);
            }

            // function to pick up localities from json.
            function getLocalityFromJson(json){
                if (!json) {
                    console.log("====> JSON IS NOT DEFINED !! <====");
                    return;
                } else {
                    console.log("json is defined so processing...");
                    var i = 0;
                    $.each(json.listinginfo, function() {
                    var loc = json.listinginfo[i].locality;
                            locationArray[i] = loc;
                            console.log("added location ->" + locationArray[i]);
                            i++;
                    });
                }
                //return locationArray;
            }

            // function to get raw json from db.
            function getJsonValues(type, url, query, getLocalityFromJson) {
                    var json;
                    // if the previous request is still pending abort.
                    if (req !== null)
                        req.abort();
                    var searchString = "";
                    if (query !== "") {
                        searchString = "searchStr" + query;
                    }       

                    console.log("searchString : (" + query + ")");
                    req = $.ajax({
                    type: type,
                            url: url,
                            data: searchString,
                            contentType: "application/json; charset=utf-8",
                            dataType: "text",
                            success: function(result) {
                            json = JSON.parse(result);
                                    console.log("========start of json 
                                                             return============");
                                    console.log(JSON.stringify(json));
                                    console.log("========end of json
                                                               return============");
                                    //return json;
                            }
                    });
                    getLocalityFromJson(json);
                    return json;
            }

the output from above code is as follows:

     searchString : () (18:25:36:473)
     at locality1.php:74
     ====> JSON IS NOT DEFINED !! <==== (18:25:36:518)
     at locality1.php:48
     ========start of json return============ (18:25:37:606)
     at locality1.php:83
     {"listinginfo":[{"listing":"1","locality":"birmingham"},       
     {"listing":"2","locality":"oxford"}]} (18:25:37:624)
     at locality1.php:84
      ========end of json return============ (18:25:37:642)
     at locality1.php:85
      > 

Help will be greatly appreciated.

call getLocalityFromJson(json); inside your success callback

function getJsonValues(type, url, query, getLocalityFromJson) {
    var json;
    // if the previous request is still pending abort.
    if (req !== null)
        req.abort();
    var searchString = "";
    if (query !== "") {
        searchString = "searchStr" + query;
    }       

    console.log("searchString : (" + query + ")");
    req = $.ajax({
        type: type,
        url: url,
        data: searchString,
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function(result) {
            json = JSON.parse(result);
            console.log("========start of json return============");
            console.log(JSON.stringify(json));
            console.log("========end of json return============");
            //return json;
            getLocalityFromJson(json);
        }
    });
}

You need to call getLocalityFromJson(json) and return json inside your ajax success function. Ajax requests are asynchronous, there's no guarantee that the request will be finished by the time you get to the lines getLocalityFromJson(json); return(json); where they are currently.

The call back functions from a jquery ajax call is complete, failure, success, etc.. Success is called after a request is successful, Failure is called if theres something like an error 500, or a 404, or w/e. Complete is Always called after a ajax call.

If you want your code to just follow sequence like in java, throw async: false into your ajax call.. but I wouldnt' recommend this as it defeats the purpose of using this method, and also locks up your browser.

You should make sure you are waiting for the request to finish before moving on - so put code in the success function that you want to run AFTER the request has finished fetching your data.

我认为您需要记住Ajax正在运行异步,因此您需要按照此线程执行刷新。

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