Is it possible to return the msg variable in javascript below out of the callback function? I tried doing this, but got a null, even though the msg variable had data in it while in the scope of the callback function.
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"); }
});
}
Not with an asynchronous request, which is the normal kind of ajax request and the preferred kind. That's because load
returns before you get your reply from the server, so obviously it can't return the msg
. Instead, have load
accept a callback:
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
}
});
}
If absolutely unavoidable , you could use a synchronous request by setting async: false
in your $.ajax
options (that's a link to the docs), then do it like this:
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;
}
But synchronous requests make for a poor user experience and, moreover, are almost never necessary, so should be avoided as much as possible.
You would need to pass a callback to load()
because the XHR is asynchronous.
BTW, msg
should contain undefined
if you don't explicitly return anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.