AJAX呼び出しが行われると、onsuccessは文字列ビルダデータを返しませんが、代わりにundefinedを返します。Javascript関数AJAX呼び出しが未定義の場合
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());
});
また、コードの異なるバージョンがいくつかありますが、正しい結果が得られません。私はAJAX呼び出しの成功関数からデータを返すにはどうすればよい
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呼び出しが行われるまでに、関数は実行を終了し、戻り変数にはまだ値が設定されていません。 UIが動的に構築されているので、UIを動的に構築する関数を追加するために文字列ビルダー関数を使用して文字列を返す必要があります。
ありがとうございます。
あなたは完全に働いたonsucess方法 –