匿名函数给出" undefined不是函数"在回调中

时间:2014-11-09 07:00:57

标签: javascript jquery ajax

当运行下面的代码时,我得到一个" Uncaught TypeError:undefined不是函数"在" back.ajax({"。我已经浏览了jQuery文档,这似乎应该可以解决这个问题。还验证了jQuery是否包含在内并且浏览器识别&# 34; $&#34 ;.定义CURRYEAR并且所有引用的元素都存在。如果我使用相同的代码作为.load()的回调,那么它执行正常,但我需要同步执行,因为while循环只执行一次如果异步调用。

代码:

function loadWL() {
  var back = $("#back-results");
  var numYears;
  var year;
  var count = 0;

  var wArr = [];
  var lArr = [];
  var dArr = [];

do {
    year = CURRYEAR - count;

    var standingsURL = STANDINGS.replace(" ", localStorage["leagueID"]);
    standingsURL = standingsURL.replace(",", year);

    var yqlStand = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + standingsURL + '"') + " #maincontainertblcell";

    //Load into the hidden pane
    var id;
    var self = this;
    back.html("");
    back.ajax({
        url: yqlStand,
        async: false
    }).done(function() {
        //Parse the number of years the league has been active
        if (count == 0) {
            numYears = $("select > option").length;
        }

        //Narrow to only the elements we need
        $(self).html($("#back-results tr .tableBody"));

        //Now traverse the back pane and store info
        $("#back-results > .tableBody a").closest("tr").each(function(index) {  
            id = urlToID($(this).find("a").attr('href'));                                       

            if (typeof wArr[id] == 'undefined') {
                wArr[id] = 0;
                lArr[id] = 0;
                dArr[id] = 0;
            }

            wArr[id] = wArr[id] + parseInt($(':nth-child(2)', this).text().trim(),10);                                  
            lArr[id] = lArr[id] + parseInt($(':nth-child(3)', this).text().trim(), 10);                                 
            dArr[id] = dArr[id] + parseInt($(':nth-child(4)', this).text().trim(), 10);                                 

            if (count == numYears-1) {
                arrayToLocal(wArr, "wins");
                arrayToLocal(lArr, "losses");
                arrayToLocal(dArr, "draws");
            }
        });

        count++;
        return;
    });
} while (count < numYears);

}

1 个答案:

答案 0 :(得分:2)

back.ajax({...})应为$.ajax({...})

ajax调用是全局的,它不依赖于任何特定对象,所以你不要在jQuery对象上调用它,你可以在jQuery命名空间对象上调用它。


此外,您确实应该修复您的ajax以使用async: true,以便在ajax调用期间不会锁定浏览器。这需要将while循环更改为可以对异步ajax调用进行排序的不同类型的结构。