2013-04-05 93 views
0

我有關於ajaxcallback功能JavaScript的AJAX回調函數不工作

一個問題,我有

test = function(){ 
    this.items=[]; 
} 

//original state. 
test.prototype.getListItems = function(){ 

    this.items.push('test item'); 
    this.handleItems(); 

} 

//this method will be called if the user clicks a button. 
test.prototype.clickBtn = function(){ 

    this.ajGetOneMoreItem()  
    this.handleItems(); 
} 

//a callback function that will add a new item. 
test.prototype.ajGetOneMoreItem = function(){ 
    var that=this;  
    ajax.callback = function(dataItem){ 
     that.items.push(dataItem); 
    }  
} 

//to show the items. 
test.prototype.handleItems = function(){ 

     //only show the test item, but not dataItem after user clicks a button. 
     console(this.items) 

} 


var testObj = new test(); 

$('#testBtn).click(function(){ 
    testObj.clickBtn(); 
}) 

我想表明,通過用戶添加新的項目。 但是,它只出現this.items只顯示第一個'test item',但沒有添加新的dataItem。我在這裏錯過了什麼嗎?非常感謝!

+0

您的AJAX調用很可能是異步的。這意味着'this.handleItems()'將在AJAX響應新數據之前運行。在你的回調之類的地方做一些日誌記錄,你會發現代碼運行不正常。 – 2013-04-05 22:38:48

+1

這必定是有數百個重複的世紀的問題。 – elclanrs 2013-04-05 22:38:57

回答

0

的調用:

this.ajGetOneMoreItem(); 

完成幾乎瞬間。這意味着下一步:

​​

發生在AJAX回調執行之前。要解決此問題,請將第二步移至回調中。

test.prototype.ajGetOneMoreItem = function(){ 
    var that=this;  
    ajax.callback = function(dataItem){ 
     that.items.push(dataItem); 
     that.handleItems(); 
    }  
} 
+0

'this.handleItems();'可能會失敗,因爲'this'很可能被重新定義。和'$('#testBtn')。click(testObj.clickBtn);'是錯誤的,因爲該方法失去了對'testObj'的引用。 OP正在做它。 – 2013-04-05 22:53:26