this code always return “0”:
function myFunc() {
var str = "0";
JQuery.ajax({
type: "POST",
url: "test.aspx/testMethod",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
alert(str); //here shows my value from my method
str = msg.d;
}
});
alert(str); //here shows "0";
return str;
But the return value of my js function is always “0”.
I think the JavaScript returns str before the ajax is completed. What I could do?
}
You are correct. Alert is being called before you hear back from the server. If you don’t want the .ajax call to return immediately, you can set async to false. Does this work?
I should point out that the way you are doing this probably isn’t the most appropriate. You are trying to create a function which works syncronously because that is simple and it’s what you are used to. However, it defeats the whole purpose of asynchronous requests, and doesn’t fit the paradigms of Javascript well. Here’s what the jQuery documentation has to say about this:
It would be better to have a callback function which uses the value that you get back from your request.