繁体   English   中英

用javascript和jquery回调

[英]Callback with javascript and jquery

我更像是一个java开发人员,并且在使用javascript回调时遇到了困难。 我想知道这里是否有专家会帮助我摆脱这段代码的困难。

我试图从db中拉出我们的位置并填充数组。 在第一次加载时,我试图刷新所有位置,我无法控制执行流和加载值。 下面是代码,我最后输入了输出。

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;
            }

上面代码的输出如下:

     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
      > 

将非常感谢帮助。

调用getLocalityFromJson(json); 在你成功的回调中

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);
        }
    });
}

你需要调用getLocalityFromJson(json)并在你的ajax成功函数中返回json。 Ajax请求是异步的,不能保证在到达getLocalityFromJson(json)行时请求将完成; 返回(JSON); 他们目前在哪里。

来自jquery ajax调用的回调函数是完成,失败,成功等。成功在请求成功后调用,如果有类似错误500,或404或w / e,则调用Failure。 完成总是在ajax调用后调用。

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

在继续之前,您应确保等待请求完成 - 因此,在请求完成获取数据之后,将代码放入要运行的成功函数中。

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

暂无
暂无

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

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