How to return a value from a function that calls $.getJSON?

喜夏-厌秋 提交于 2019-11-26 14:16:59

问题


function lookupRemote(searchTerm)
{
   var defaultReturnValue = 1010;
   var returnValue = defaultReturnValue;

   $.getJSON(remote, function(data)
   {
      if (data != null)
      {
           $.each(data.items, function(i, item)
           {
               returnValue = item.libraryOfCongressNumber;
           });
      }
    });
    return returnValue;
}

Why is the returnValue from this function alway equal to the default value set at the beginning of the function and never to the value retrieved from the JSON lookup?


回答1:


This happens because that callback function (function(data) {...}) runs later when the response comes back...because it's an asynchronous function. Instead use the value once you have it set, like this:

function lookupRemote(searchTerm)
{
    var defaultReturnValue = 1010;
    var returnValue = defaultReturnValue;
    $.getJSON(remote, function(data) {           
        if (data != null) {
              $.each(data.items, function(i, item) {                 
                    returnValue = item.libraryOfCongressNumber;
              });
        }
        OtherFunctionThatUsesTheValue(returnValue);
     });
}

This is the way all asynchronous behavior should be, kick off whatever needs the value once you have it...which is when the server responds with data.




回答2:


If you don't want to use asynchronous function, better use the following:

function getValue(){
   var value= $.ajax({ 
      url: 'http://www.abc.com', 
      async: false
   }).responseText;
   return value;
}

This function waits until the value is returned from the server.




回答3:


The function you pass to getJSON is run when the response to the HTTP request arrives which is not immediately.

The return statement executes before the response, so the variable hasn't yet been set.

Have your callback function do what needs doing with the data. Don't try to return it.



来源:https://stackoverflow.com/questions/4200641/how-to-return-a-value-from-a-function-that-calls-getjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!