zl程序教程

您现在的位置是:首页 >  前端

当前栏目

bootstrap+jquery+ajax跨域实现一个聊天机器人

BootstrapjQuery机器人AJAX跨域 实现 一个 聊天
2023-09-27 14:26:50 时间

bootstrap+jquery+ajax跨域实现一个聊天机器人


  • 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
  • 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩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