-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的函数。
预先感谢您。
你必须在onsucess方法 –