简体   繁体   English

用javascript和jquery回调

[英]Callback with javascript and jquery

I am more of a java developer and am having difficulty with javascript callback. 我更像是一个java开发人员,并且在使用javascript回调时遇到了困难。 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. 我试图从db中拉出我们的位置并填充数组。 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: 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); 调用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. 你需要调用getLocalityFromJson(json)并在你的ajax成功函数中返回json。 Ajax requests are asynchronous, there's no guarantee that the request will be finished by the time you get to the lines getLocalityFromJson(json); Ajax请求是异步的,不能保证在到达getLocalityFromJson(json)行时请求将完成; return(json); 返回(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. 来自jquery ajax调用的回调函数是完成,失败,成功等。成功在请求成功后调用,如果有类似错误500,或404或w / e,则调用Failure。 Complete is Always called after a ajax call. 完成总是在ajax调用后调用。

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. 如果你希望你的代码像java中那样遵循序列,请将async: false抛入你的ajax调用中......但是我不推荐这样做,因为它违背了使用这种方法的目的,并且还锁定了你的浏览器。

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正在运行异步,因此您需要按照此线程执行刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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