bootstrap+jquery+ajax跨域实现一个聊天机器人
2023-09-27 14:26:50 时间
- 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
- 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
目录结构
效果图
原始界面
回复界面
全部代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>图灵机器人</title>
<link rel="stylesheet"
href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<style>
*{margin: 0;padding: 0;}
ul{list-style:none;width: 400px;height: 100%;}
ul li{clear:both;margin:5px 0;color:white;}
img{width: 50px;height: 50px;border-radius: 50%;}
.box{
width: 400px;
height: 600px;
background:url('./img/bg.jpg');
margin:100px auto;
text-align: center;
}
.box .name{
color:skyblue;
font-size:24px;
padding:5px;
}
.box .bot{
margin-top:500px;
}
.box .bot .row #msg{
margin-left:60px;
margin-right:30px;
}
</style>
</head>
<body>
<div class="box">
<div class="name">聊天机器人</div>
<div class="top">
<ul class="info">
</ul>
</div>
<div class="bot">
<div class="row">
<input type="text" id="msg" class="form-control col-sm-6">
<button class="btn btn-success " id="btn">发送</button>
</div>
</div>
</div>
<script src="./jquery.min.js"></script>
<script>
$('#btn').click(function(){
var $msg=$("#msg").val();
var $li=$('<li><span class="me">'+$msg+'</span><img src="./img/me.jpg"/></li>');
$li.css('float',"right");
$(".info").append($li);
$.post("http://www.tuling123.com/openapi/api",{
"key":"youappkey",//图灵机器人为每个注册用户的机器人分配的秘钥
"info":$msg
},function(data){
var $li=$('<li><img src="./img/yy.jpg"/><span >'+data.text+'</span></li>');
$li.css('float',"left");
$(".info").append($li);
$("#msg").val("");
})
})
</script>
</body>
</html>
关于原理
- 其实核心就是ajax异步跨域请求拉数据
- 输入框填写内容点击按钮后,在右侧创建聊天框(头像+文本)并发出ajax请求
- 数据回来后,在回调函数中创建机器人的回复框,原理同上
- 调用的是图灵机器人的接口,我只写的布局和调用而已
- 下面是图灵机器人官网,注册,创建机器人后,有官方文档可以参考
- 注意,不要设置开启秘钥,否则会请求失败
- 最后提个小建议, 在线引用静态资源如(jquery,bootstrap,模板引擎…),推荐CDN
相关文章
- 8个强大的基于Bootstrap的CSS框架
- BootStrap fileinput.js文件上传组件实例代码
- jQuery 实现 bootstrap 模态框 删除确认
- 文件上传控件bootstrap-fileinput的使用
- BootStrap让两个控件在一行显示
- BootStrap 经常使用控件总结
- Bootstrap 简介
- bootstrap 失效的原因
- Bootstrap学习笔记1--表单样式
- Error: Bootstrap's JavaScript requires jQuery错误 boostrap下拉菜单无效Angular is running in the development
- 利用BootStrap创建搜索框 详解
- Angular学习笔记【ngx-bootstrap】中的 tabset
- bootstrap 日期控件常用选项
- bootstrap 日期控件起始日期&结束日期相互约束
- 在 vue-cli 脚手架中引用 jQuery、bootstrap 以及使用 sass、less 编写 css [vue-cli配置入门]
- 19前端学习之JQuery基础(三):jQuery尺寸、位置操作、jQuery事件、jQuery事件对象、Jquery拷贝对象、jQuery 多库共存、jQuery 插件