Javascript 如何从调用 $.getJSON 的函数返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4200641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:21:28  来源:igfitidea点击:

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

javascriptjqueryreturn-valuegetjson

提问by Gareth

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 returnValuefrom 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?

为什么returnValuefrom this function 总是等于在函数开头设置的默认值,而不是从 JSON 查找中检索到的值?

回答by Nick Craver

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

发生这种情况是因为该回调函数 ( function(data) {...})在响应返回时稍后运行......因为它是一个异步函数。而是在设置后使用该值,如下所示:

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.

这是所有异步行为的方式,一旦你拥有它,就开始需要它的任何东西......这是服务器响应数据的时候。

回答by JLavoie

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.

此函数一直等到该值从服务器返回。

回答by Quentin

The function you pass to getJSONis run when the response to the HTTP request arriveswhich is notimmediately.

你传递给函数getJSON运行时的HTTP请求的响应到达这是不是马上。

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

return 语句响应之前执行,因此尚未设置变量。

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

让您的回调函数执行需要对数据执行的操作。不要试图退货。