weixin_33733810 2016-06-24 03:57 采纳率: 0%
浏览 82

jQuery等待响应

It's been awhile since I worked with query and I can't for the life of me figure out why this isn't waiting on the response. I looked for answers similar to this post. I must be missing something pretty simple.

The calling function:

$('#cappuccino-button').click(function () {
    $('#screen-one').hide();    
    var hasMilk = IsThereMilk();
    if (hasMilk) {
        $('#cappuccino-success').show();
    } else {
        $('#milk-fail').show();
    }
}

The function itself:

function IsThereMilk() {
    $.ajax({
        url: 'http://milkstore/gotany',
        type: 'GET',
        async: false,
        success: function(data){ 
            console.log('*****AJAX' + data.hasMilk);
            return data.hasMilk;
        }
    });
}

Can anyone help me identify why my calling function isn't waiting on the ajax request?

  • 写回答

3条回答 默认 最新

  • weixin_33744854 2016-06-24 04:04
    关注

    IsThereMilk() call does not actually return a value. Though if $.ajax() was returned the value would be a jQuery promise object, not a Boolean.

    Try adjusting js, to return $.ajax() from IsThereMilk() call, .then() to check if response data.hasMilk

    function IsThereMilk() {
        return $.ajax("http://milkstore/gotany");
    }
    
    $("#cappuccino-button").click(function () {
        $("#screen-one").hide();    
        var hasMilk = IsThereMilk();
        hasMilk.then(function(data) {
          if (data.hasMilk) {
            $("#cappuccino-success").show();
           } else {
            $("#milk-fail").show();
           }
        })
    })
    

    jsfiddle https://jsfiddle.net/r8hc6nna/

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题