可以用这个接口“https://api.ownthink.com/bot”写一个能在浏览器对话机器人吗
时间: 2023-06-01 13:02:58 浏览: 173
可以,但需要使用JavaScript和AJAX技术。以下是一个简单的实现示例:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>对话机器人</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
border-radius: 5px;
overflow: hidden;
}
.message {
margin-bottom: 10px;
padding: 10px;
border-radius: 5px;
background-color: #f2f2f2;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.message.bot {
background-color: #e6f7ff;
}
.message.user {
background-color: #fff2e6;
text-align: right;
}
input[type=text] {
width: 100%;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #f2f2f2;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
box-sizing: border-box;
font-size: 16px;
}
button {
display: block;
margin: 10px auto 0;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #008CBA;
color: #fff;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #006d87;
}
</style>
</head>
<body>
<div class="container">
<h1>对话机器人</h1>
<div id="messages"></div>
<input type="text" id="input" placeholder="输入消息...">
<button id="send">发送</button>
</div>
<script>
var messages = document.getElementById('messages');
var input = document.getElementById('input');
var send = document.getElementById('send');
send.addEventListener('click', function() {
var text = input.value.trim();
if (text) {
addMessage(text, 'user');
getResponse(text);
input.value = '';
}
});
function addMessage(text, className) {
var message = document.createElement('div');
message.classList.add('message', className);
message.textContent = text;
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
}
function getResponse(text) {
var xhr = new XMLHttpRequest();
var url = 'https://api.ownthink.com/bot';
var data = 'spoken=' + text;
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
var text = response.data.info.text;
addMessage(text, 'bot');
}
};
xhr.send(data);
}
</script>
</body>
</html>
```
这个页面包含一个输入框、一个发送按钮和一个消息列表。当用户输入文本并点击发送按钮时,页面会向接口发送POST请求,获取到机器人的回复并在消息列表中显示出来。
阅读全文