2015-08-15 121 views
0

下面是我使用的代碼。我正在嘗試執行「回調」,因爲在腳本中使用ajax會有多個不同的調用,因此我想要一個函數來處理所有這些。這是以下功能的最基本版本。jquery ajax返回undefined json

function gd(callback){ 

$.ajax(
    { 
     type: "GET", 
     dataType: "json", 
     url: ad + "?a=vocab&lessonID=" + lessonID + "&offset=" + offset + '&nocache=' + (new Date()).getTime(), 
     success: function(response) { 
     callback(response);  
     }, 
     error: function(jqXHR, exception) {alert('error');}  
    }); 
} 

function test(response){ 
    alert('hi' + response); 
} 

gd(test()); // returns undefined 

我怎樣才能讓這個我不得到不確定的和正確獲得JSON對象要能夠調用GD後對其進行操作測試()函數中(測試())

回答

2

你應通過回調函數testgd的引用。按照您當前的實現,當使用()時,該函數被調用。

所以使用

gd(test); 

,而不是

gd(test()); 

當調用方法test(),你不傳遞任何價值,放慢參數response從而獲得undefined

0

如果使用括號()

gd(test()) 

您在啓動ajax調用之前調用該函數。您應該將指針傳遞給該功能,而不是其結果...

所以gd(test)