jQuery Ajax返回:未定义 [英] jquery ajax return: undefined

查看:149
本文介绍了jQuery Ajax返回:未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定您知道此问题,但我仍在尝试解决几天.我已经尝试了很多东西,但是没有人起作用:

I'm sure you know this problem, I'm still trying to solve it for few days. I've tried lots of stuff but no one worked:

这是代码

function lobbyLeader() {
    $.ajax({
       data: {"id": 1, "request": "lobbyinfo", "method": "read"},
       url: 'api.php',
       dataType: 'json',
       success: function(data){
           result = data.leader;
           return result;
       }
   });
}

alert(result);将显示1,但是在其他功能中使用时会显示undefined.

alert(result); will show 1 but when using in an other function it says undefined.

推荐答案

您不能从这样的异步函数中return,而是从该success回调函数而不是父函数返回.相反,请在回调中启动所需的任何内容,例如:

You can't return from an asynchronous function like this, you're returning from that success callback function, not the parent function. Instead, kick off whatever you need in the callback, like this:

function lobbyLeader() {
  $.ajax({
    data: {"id": 1, "request": "lobbyinfo", "method": "read"},
    url: 'api.php',
    dataType: 'json',
    success: function(data){
      someOtherFunc(data.leader);
   }
 });
}

这篇关于jQuery Ajax返回:未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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