开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜