函数在执行期间“超出”if-else语句

时间:2013-12-05 00:54:10

标签: javascript jquery post if-statement asynchronous

我有以下功能:

function updateChatRoom() {
$.post('php/api.php', {"function":"getActiveChat"}, function(jsData) {
    var chatID = jsData.id;
    if (chatID == 0) {
        alert('no active chat!');
    }
    else {
        $.post('php/api.php', {"function":"updateChatRoom", "chatID":chatID}, function(jsData) {
            $('#chatRoom').empty();
            length = jsData.length;
            for (i=0; i<length; i++) {
                $('#chatRoom').append('\
                    <div class="fe-message-wrap">\
                        <div class="fe-message-name">'+ jsData[i].name + ':</div>\
                        <div class="fe-message-text">'+ jsData[i].message +'</div>\
                    </div>\
                ').fadeIn('250');
            }
            $('#chatRoom').scrollTop($('#chatRoom')[0].scrollHeight).animate('500');
            $('#chatMessage').focus();
        });
    }
});

}

执行此功能时,应首先检查是否存在活动聊天。这是通过api调用&#34; getActiveChat&#34;来测试的。 如果没有活动聊天室,则返回0。 我的问题是,即使返回0 ind chatID,它也会忽略整个if-else语句并跳转到下一个$ .post()函数... ????那怎么样? 我不明白,有什么不对?

任何提示?

1 个答案:

答案 0 :(得分:3)

检查chatID是否为字符串。在javascript 0 == false"0" == true


现在您提到chatID的值未定义,您已找到原因。因为在javascript中,undefined != 0

检查jsData是什么。如果是字符串,那么您需要执行JSON.parse()将其转换为对象。