如何使用Watson Conversation在屏幕上显示多条消息

时间:2016-12-15 09:40:34

标签: javascript ibm-cloud watson-conversation

我正在使用Watson技术的聊天机器人,更准确地说是使用会话服务。这是我在Bluemix上的第一个应用程序和javascript,我的聊天机器人的显示消息有问题。我解释一下:目前我有这段代码:

var text = response.output.text[0]; // only display first value

我的功能displayMessage

function displayMessage(text, user) {

        var chat = document.getElementById('chatBox');
        var bubble = document.createElement('div');
        bubble.className = 'message';  // Wrap the text first in a message class for common formatting

        // Set chat bubble color and position based on the user parameter
        if (user === watson) {
            bubble.innerHTML = "<div class='bot'>" + text + "</div>";
        } else {
            bubble.innerHTML = "<div class='user'>" + text + "</div>";
        }

        chat.appendChild(bubble);
        chat.scrollTop = chat.scrollHeight;  // Move chat down to the last message displayed
        document.getElementById('chatMessage').focus();

        return null;
}

目前的问题是该函数只显示我的第一个值,但在某些情况下我必须显示n个消息(n总是<10) 所以我考虑创建一个数组[10]来存储我的消息while (array[i] != undefined)。但我的错误是在displayMessage函数中显示 - 我不知道如何显示几条消息。我试过这个:

bubble.innerHTML = "<div class='bot'>" + tab[tmp] + "</div>";

和一个循环,但与我的声明相同,但它不起作用。

有人可以帮助我吗?

谢谢

编辑n°1 要通知您这是我创建标签时的第一个循环:

var tab = new Array(response.output.text[0]); // array with my different text
        var tmp = 1;
        while(response.output.text[tmp] != undefined){
            tab[tmp] = response.output.text[tmp]; // only display first value if second is null
            tmp = tmp + 1;
    }

2 个答案:

答案 0 :(得分:1)

有一种更简单的方法。 JS允许你加入&#39;数组中的所有元素:

text = response.output.text.join(" ");

这应该可以做到!

答案 1 :(得分:0)

我找到了一个解决方案,一个小野人,但它现在正在工作,所以如果有人有更好的解决方案我会接受它。

我在我的帖子中创建了一个数组,然后当我实现我的bubber.innerHTML时,

bubble.innerHTML = "<div class='bot'>" + tab[0] + tab[1]+ tab[2] + tab[3] + tab[4] +tab[5] + tab[6]+ tab[7]+ "</div>";

因为我的数组总是高于7