问题
I have a simple function which only returns a translated message from the server to the client. But the result shows undefined, when I pass the result into a var.
function MessageNoResult() {
$.ajax(
{
type: "POST",
async: true,
url: '<%= ResolveUrl("~/WebMethods.aspx/MessageNoResult") %>',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
return msg.d;
}
});
}
Result --> Undefined (bad)
var message = MessageNoResult();
alert(message);
When I look into the Headers it gives me:
Server ASP.NET Development Server/9.0.0.0
Date Wed, 09 Nov 2011 09:01:31 GMT
X-AspNet-Version 2.0.50727
Cache-Control private, max-age=0
Content-Type application/json; charset=utf-8
Content-Length 24
Connection Close
Response {"d":"No search result"}
JSON d "No search result"
Why do I still get an undefined result?
回答1:
You can pass a callback function to the MessageNoResult
function
function MessageNoResult(callback) {
$.ajax(
{
type: "POST",
async: true,
url: '<%= ResolveUrl("~/WebMethods.aspx/MessageNoResult") %>',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
callback(msg);
}
});
}
And then call:
MessageNoResult(function(msg) {
alert(msg.d);
});
回答2:
The ajax call is still being executed as your code moves on to the alert(message)
line, so the message
variable has no value.
You need to pass the value of the response to a function within the success
method.
success: function(msg) {
myFunction(msg.d);
}
// outside ajax call
function myFunction(ajaxValue) {
alert(ajaxValue)
}
回答3:
The ajax call is an async call and you’re running the alert right after the MessageNoResult, thus the message has no value until you’ve actually completed the ajax request.
You’ll need to run your alert inside the success from ajax call.
回答4:
You are trying to return from success which is a callback function. Set a global variable and use it within the success function retmess = msg.d
to store the return or set the content of an html element jQuery('#status').html(msg);
回答5:
Your code:
var message = MessageNoResult();
is setting the message
variable to the return value of the MessageNoResult
functiion. Since you have no return value in this function, you get undefined
as response.
The corrcet way to handle this is by dealing with the return value from the Ajax call inside the success
callback.
For a similar question see my answer here:
来源:https://stackoverflow.com/questions/8062574/jquery-ajax-results-in-undefined