不適用於異步請求,這是正常類型的ajax請求和首選類型。這是因爲load
在您收到服務器的回覆之前會返回,所以顯然它不能返回msg
。相反,有load
接受回調:
load(function(msg) {
// Use msg here
});
function load(callback)
{
$.ajax({
type: "POST",
url: "myPage.aspx/MyMethod",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Call our callback with the message
callback(msg);
},
failure: function() {
// Call our callback with an indication things failed
callback(null); // Or however you want to flag failure
}
});
}
如果絕對少不了,你可以通過設置在$.ajax
選項(這是該文檔的鏈接),然後再去做這樣async: false
使用同步請求:
var msg = load();
function load(callback)
{
var result;
$.ajax({
type: "POST",
url: "myPage.aspx/MyMethod",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
// Set the `result` value here. We can't *return* it
// here because, of course, that would just return it
// from our `success` function.
result = msg;
},
failure: function() {
result = null; // Or however you want to flag failure
}
});
// Because we've made the request synchronous, we won't get here
// until the ajax call is complete and `result` has been set by
// the callbacks above; we can now return it.
return result;
}
但同步請求作出較差的用戶體驗,而且,幾乎從來沒有必要的,所以應避免多儘可能。
可能重複的[Return「success:」方法的數據?](http://stackoverflow.com/questions/7753844/return-success-methods-data) – Quentin
@Quentin:這個問題實際上也是重複的和其接受的答案是相當差),[這另一個](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success)有更好的答案(雖然仍然沒有演示回調和單獨的同步請求)。 –