2016-08-21 126 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