是否可以将javascript中的msg变量从回调函数中返回?我尝试这样做,但得到一个null,即使msg变量在回调函数的范围内有数据。
var msg = load();
function load()
{
$.ajax({
type: "POST",
url: "myPage.aspx/MyMethod",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { return msg; // Doesn't return anything because
//it's automatically called on success???
},
failure: function () { alert("Failure"); }
});
}
答案 0 :(得分:3)
不是异步请求,这是正常的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;
}
但 同步 请求会导致糟糕的用户体验,而且几乎不需要,所以应该尽可能避免。
答案 1 :(得分:0)
您需要将回调传递给load()
,因为XHR是异步的。
BTW,如果您没有明确地返回任何内容,则msg
应包含undefined
。