如何从调用$ .getJSON的函数返回一个值? [英] How to return a value from a function that calls $.getJSON?

查看:165
本文介绍了如何从调用$ .getJSON的函数返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

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

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?

推荐答案

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

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.

这篇关于如何从调用$ .getJSON的函数返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆