用javascript和jquery回调

时间:2014-03-06 13:08:41

标签: javascript php jquery callback

我更像是一名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
      > 

非常感谢帮助。

4 个答案:

答案 0 :(得分:2)

在成功回调中调用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);
        }
    });
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

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