Returning a variable within an ajax call
If I have the following ajax call (inside a function) how do I go about returning the 'test' variable, in this case a string for testing purposes? Currently i'm getting test is not defined.
function getMaps(){
mapID = "us";
$.ajax({
type: "GET",
url: "getMap.asp",
data: "mapID=" + mapID,
contentType: "application/json; charset=utf-8",
dataType: "json",
asy开发者_高级运维nc: false,
success: function(response) {
var test = 'text string';
}
});
return test;
};
function getMaps(){
mapID = "us";
var test="";
$.ajax({
type: "GET",
url: "getMap.asp",
data: "mapID=" + mapID,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
test = 'text string';
}
});
return test;
};
Try to open a pop-up box or set the value of some text field instead. The response function you defined will get called asynchronously.
Also, "test" is not defined within the scope of the function from which it is returned. Move the definition to the top of that function -- it shouldn't be undefined, but it will still not solve the issue.
var
right before test
means that the variable will be visible only inside that anonymous function
精彩评论