doumi0737 2014-08-27 19:34
浏览 31
已采纳

涉及AJAX的函数不返回值 - jQuery [重复]

This question already has an answer here:

I have a document.ready function like this;

  function myfun(){
    var xx;
    $.ajax({
        type: 'POST',
        url: 'handler.php',
        cache: false,
        success: function(result) {
          xx = result;
        },
    });
    return xx;
  }


  var a;
  a = myfun();
  alert(a);

handle.php is set to echo 1234. But I am getting alert as "undefined". How can I fix this? Expected alert is "1234" (the reply from ajax handler).

</div>
  • 写回答

3条回答 默认 最新

  • dongquan0024 2014-08-27 19:37
    关注

    It's asynchronous. Use a callback:

    function myfun(){
    
        return $.ajax({
            type: 'POST',
            url: 'handler.php',
            cache: false
        });
    }
    
    myfun().done(function(data){
        console.log(data);
    });
    

    Or if you're using an old jQuery version without deferred objects:

    function myfun(done){
    
        $.ajax({
            type: 'POST',
            url: 'handler.php',
            cache: false,
            success: done
        });
    }
    
    myfun(function(data){
        console.log(data);
    });
    

    https://stackoverflow.com/search?q=ajax+not+returning+data

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题