2015-08-15 124 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)