2013-04-05 92 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