2012-12-29 38 views
0

我有從ajax返回數據到調用函數的問題。當我console.logging它沒有定義。從函數返回的數據是未定義的

我相信我的問題發生是因爲js是異步的,而當我是console.logging數據時,它還沒有準備好。我能做些什麼來解決它?

FooFunction: function(userInput){ 

    var fooData = FooFunction2(userInput); 
    console.log(fooData);  // <--- undefined 
}, 

FooFunction2: function(userInput) { 

    $.ajax({ 
     url:'./php/test.php', 
     type:'post', 
     dataType:'json', 
     data:{ 
      fooData: userInput 
     }, 
     success:function(data) { 
      ...manipulating the data... 

      console.log(manipulatedData); // <--- ['foo', 'foo2']; 
      return manipulatedData; 
     } 
    }); 
}, 
+0

請出示什麼'的console.log(數據);'節目。 – AlecTMH

+0

它來自哪裏以及在哪裏定義** userInput ** ??你沒有說這個例子,你應該檢查var開始的位置 – sbaaaang

回答

2

Ajax調用是異步的,所以返回時,將無法正常工作。將代碼更改爲使用在ajax調用完成時調用的回調。

我改變了你的代碼,這樣做:

FooFunction: function(userInput){ 
    var callbackfunc = function(ajaxData) 
    { 
     console.log(ajaxData); //ajax is complete! 
    }; 

    this.FooFunction2(userInput, callbackfunc); 
}, 

FooFunction2: function(userInput, callbackfunc) { 

    $.ajax({ 
     url:'./php/test.php', 
     type:'post', 
     dataType:'json', 
     data:{ 
      fooData: userInput 
     }, 
     success:function(data) { 
      ...manipulating the data... 

      console.log(manipulatedData); // <--- ['foo', 'foo2']; 
      callbackfunc(manipulatedData); 
     } 
    }); 
}, 
1

FooFunction2是對象的屬性中使用this.FooFunction2

,你不能從異步方法返回。要麼使ajax呼叫同步或proivde回調。

FooFunction: function(userInput){ 

    var fooData = this.FooFunction2(userInput); 
    console.log(fooData);  // <--- undefined 
}, 

修改代碼

FooFunction: function(userInput){ 

    this.FooFunction2(userInput, function(fooData){ 
      console.log(fooData);  // <--- undefined 
    }); 

}, 

FooFunction2: function(userInput, cb) { 

    $.ajax({ 
     url:'./php/test.php', 
     type:'post', 
     dataType:'json', 
     data:{ 
      fooData: userInput 
     }, 
     success:function(data) { 
      ...manipulating the data... 

      console.log(manipulatedData); // <--- ['foo', 'foo2']; 
      cb(manipulatedData); 
     } 
    }); 
}, 
+0

@undefined:是的,它的確如此。解決不能從異步函數返回的方法是使用回調。 – Eric