javascript函数返回值混淆

lan*_*ng2 4 javascript ajax

我不清楚以下虚拟代码的返回值:

function foo()
  var ret = 0;
  var xhr=send_request( "bla", function() {
      // do something with the AJAX response
      // based on the value of response, var ret get set
  } );
  return ret;
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是:基于AJAX响应,我可能会再次尝试请求.但无论如何,上面的函数总是返回0.

显然我可以让foo()函数决定在需要时调用send_request()两次,但它有点难看.有一个简单而好的方法吗?

谢谢

riw*_*alk 7

您正在尝试同步进行ajax调用,但您正在进行异步调用.

重要的是要了解编写它的方式,代码不会等到AJAX调用完成后再转到下一行.因此,它总是返回初始值ret.

做几件事来解决这个问题:

  • 使用jQuery(如果你还没有)
  • 使用jQuery的ajax()函数,并设置async为false.

应该看起来像这样:

function foo()
    var ret = $.ajax({ url: "blah",
                       async: false
                     }).responseText;

    // do your stuff here

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

编辑:可以通过异步调用执行此操作,但您必须调整您对问题的思考方式.您不必考虑返回值,而必须考虑回调函数.

为了举例,我想说我正在尝试获取用户的名字并将其放在页面上.我的代码看起来像这样:

function GetUsername() {
    $.ajax( { url: "blah",
              success: PopulateUsername    // Specify a callback
            });
    // I don't do anything else. Execution will continue when the
    // callback gets called from the AJAX call.
}

function PopulateUsername(data) {
    alert(data);
    // Anything else I want to do, I do here, because it is only 
    // here that I have access to the result.
}

GetUsername();  // I call GetUsername() here, and that's it. Any
                // further actions that need to happen are going to
                // occur in the callback function
Run Code Online (Sandbox Code Playgroud)

  • 是的,但它涉及重构您的代码(以及调整您对事物的思考方式).我会做一个快速编辑. (2认同)