开发者

Get json value from a function that has an ajax call in it

I'm trying to get json value from a function that has an ajax call in it.

This is my function:

function getVariables(){

     $.ajax({
      type: "post",
      url: "db/functions.php",
      data: "func=getvars,
      dataType: "json",
      success: function(response)
      {        
        return { 
          'var1': response.var1,
          'var2': response.var2
        };
      }
    })开发者_运维技巧;     
}

I am trying to use this in my javascript to get var1 var firstvar = getVariables().var1;

when I set an alert in getVariables function it returns var1 and var2, already checked that out. So the only part which is not working properly is: var firstvar = getVariables().var1;


That's not going to work. The AJAX call is asynchronous, and needs to wait for the http request to complete before you can use it's return values.

You can make the AJAX call synchronous, but that's probably going to introduce an unnecessary delay. Typically the better option is to use the variables directly in your callback "success" function.


Your anonymous success function returns var1 and var2 (to nowhere), but getVariables is not returning them. It cannot in fact, because it has exited before the asynchronous JSON call is complete. Even if it was synchronous, you still aren't returning the return value of the anonymous "sub-function".

EDIT: You could do something like this:

function getVariables(){

    var response = $.ajax({
      type: "post",
      url: "db/functions.php",
      data: "func=getvars,
      dataType: "json",
      async: false
    });
    return {'var1': response.var1,
            'var2': response.var2}  
}

See how the return statement is now in getVariables, not in a function INSIDE getVariables? So now getVariables will return the values.

Although be careful of using async: false, it can lock the browser.


There are two problems with this:

Ajax calls, by default, are asynchronous. This means that the success function will not be invoked until sometime after getVariables has returned. You need to alter the settings of you ajax call so that it is synchronous.

Your second problem is that the values are returned from the success function, but that does not return them from the getVariables function. You need to return the variables from function scope.

Below is the same function, but with the async option set to false and with the values returned from the function's scope.

function getVariables(){
     var rv = undefined;
     $.ajax({
      async : false,
      type: "post",
      url: "db/functions.php",
      data: "func=getvars",
      dataType: "json",
      success: function(response)
      {        
        rv = { 
          'var1': response.var1,
          'var2': response.var2
        };
      }
    });     
    return rv;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜