2016-08-21 127 views
-1

當進行AJAX調用時,onsuccess不會返回字符串構建器數據,而是返回undefined。Javascript函數AJAX調用返回undefined

var MyApp = window.MyApp || {}; 

MyApp.Data = function() { 
    var temp = 'Test', 
    ShowMethod = function() { 
     $.ajax({ 
      url: "some url", 
      type: "GET", 
      headers: { 
       "accept": "application/json; odata=verbose" 
      }, 
      success: ShowMethodSucceeded, 
      error: FailedMethod 
     }); 
    }, 
    ShowMethodSucceeded = function(data) { 
     var results = data.d.results; 
     if(results.length > 0) { 
      temp = ''; 
      for(var i = 0; i < results.length; i++) { 
       temp += 'string builder stuff'; 
      } 
     } else { 
      alert('no records'); 
     } 
     return temp; 
    }, 
    FailedMethod = function() { 
     alert('error'); 
    }; 
    return { 
     Show: ShowMethod 
    }; 
}(); 

$(document).ready(function() { 
    $('#divResults').append(MyApp.Data.Show()); 
}); 

此外,這裏有幾個不同版本的代碼不會收穫正確的結果。

MyApp.Data = function() { 
    var temp = 'Test', 
    ShowMethod = function() { 
     $.ajax({ 
      url: "some url", 
      type: "GET", 
      headers: { 
       "accept": "application/json; odata=verbose" 
      }, 
      success: ShowMethodSucceeded, 
      error: FailedMethod 
     }); 
    }, 
    return temp; 
    // returns 'Test' instead of the string builder 

MyApp.Data = function() { 
    var temp = 'Test', 
    ShowMethod = function() { 
     $.ajax({ 
      url: "some url", 
      type: "GET", 
      headers: { 
       "accept": "application/json; odata=verbose" 
      }, 
      success: function(data) { temp = data; }, 
      error: FailedMethod 
     }); 
    }, 
    return temp; 
    // returns 'Test' instead of the JSON from data 

如何從AJAX調用的成功函數中返回數據?

在進行AJAX調用時,函數完成執行並且返回變量尚未填充。 UI是動態構建的,我想使用字符串構建器函數來返回字符串以附加動態構建UI的函數。

預先感謝您。

+0

你必須在onsucess方法 –

回答

2

我想你會需要在整個下探回調,像這樣:

MyApp.Data = function() { 
    var temp = 'Test', 
    ShowMethod = function(cb) { // added cb 
     $.ajax({ 
      url: "some url", 
      type: "GET", 
      headers: { 
       "accept": "application/json; odata=verbose" 
      }, 
      success: function (data) { 
       ShowMethodSucceeded(data, cb); // pass cb through 
      }, 
      error: FailedMethod 
     }); 
    }, 
    ShowMethodSucceeded = function(data, cb) { // added cb 
     var results = data.d.results; 
     if(results.length > 0) { 
      temp = ''; 
      for(var i = 0; i < results.length; i++) { 
       temp += 'string builder stuff'; 
      } 
     } else { 
      alert('no records'); 
     } 
     cb(temp); // call cb with the result 
    }, 
    FailedMethod = function() { 
     alert('error'); 
    }; 
    return { 
     Show: ShowMethod 
    }; 
}(); 

$(document).ready(function() { 
    MyApp.Data.Show(function (result) { // pass a callback 
     $('#divResults').append(result); // use the result 
    }); 
}); 
+0

這工作完全恢復溫度!我花了數小時試圖弄清楚這一點。感謝您抽出時間用簡單的英語解釋它! – detailCode