-
6. 简单搭建一个聊天界面
-
接口调用
我们异步请求服务端接口,并将结果渲染到界面
$.ajax({
type: 'post',
url: AppDomain+'chat',
async: true,//异步
dataType: 'json',
data: (
{
"msg":request_txt
}),
success: function (data)
{
console.log(JSON.stringify(data));
if (data.is_success == true) {
setView(resUser,data.message);
}
},
error: function (data)
{
console.log(JSON.stringify(data));
}
});//end Ajax
-
7、目录结构
-
8、Python服务端代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
import os
import aiml
os.chdir('./src/alice')
alice = aiml.Kernel()
alice.learn("startup.xml")
alice.respond('LOAD ALICE')
define('port', default=3999, help='run on the given port', type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', MainHandler),
(r'/chat', ChatHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), 'templates'),
static_path=os.path.join(os.path.dirname(__file__), 'static'),
debug=True,
)
# conn = pymongo.Connection('localhost', 12345)
# self.db = conn['demo']
tornado.web.Application.__init__(self, handlers, **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
def post(self):
result = {
'is_success': True,
'message': '123'
}
respon_json = tornado.escape.json_encode(result)
self.write(str(respon_json))
def put(self):
respon_json = tornado.escape.json_encode("{'name':'qixiao','age':123}")
self.write(respon_json)
class ChatHandler(tornado.web.RequestHandler):
def get(self):
self.render('chat.html')
def post(self):
try:
message = self.get_argument('msg', None)
print(str(message))
result = {
'is_success': True,
'message': str(alice.respond(message))
}
print(str(result))
respon_json = tornado.escape.json_encode(result)
self.write(respon_json)
except Exception, ex:
repr(ex)
print(str(ex))
result = {
'is_success': False,
'message': ''
}
self.write(str(result))
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
print('HTTP server starting ...')
main()
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="qixiao.ico" type="image/x-icon"/>
<title>qixiao tools</title>
<link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css">
<script type="text/javascript" src="../static/js/jquery-3.2.0.min.js"></script>
<script type="text/javascript" src="../static/js/bootstrap.min.js"></script>
<style type="text/css">
.top-margin-20{
margin-top: 20px;
}
#result_table,#result_table thead th{
text-align: center;
}
#result_table .td-width-40{
width: 40%;
}
</style>
<script type="text/javascript">
</script>
<script type="text/javascript">
var AppDomain = 'http://localhost:3999/'
$(document).ready(function(){
$("#btn_sub").click(function(){
var user = 'qixiao(10011)';
var resUser = 'alice (3333)';
var request_txt = $("#txt_sub").val();
setView(user,request_txt);
$.ajax({
type: 'post',
url: AppDomain+'chat',
async: true,//异步
dataType: 'json',
data: (
{
"msg":request_txt
}),
success: function (data)
{
console.log(JSON.stringify(data));
if (data.is_success == true) {
setView(resUser,data.message);
}
},
error: function (data)
{
console.log(JSON.stringify(data));
}
});//end Ajax
});
});
function setView(user,text)
{
var subTxt = user + " "+new Date().toLocaleTimeString() +'\n·'+ text;
$("#txt_view").val($("#txt_view").val()+'\n\n'+subTxt);
var scrollTop = $("#txt_view")[0].scrollHeight;
$("#txt_view").scrollTop(scrollTop);
}
</script>
</head>
<body class="container">
<header class="row">
<header class="row">
<a href="/" class="col-md-2" style="font-family: SimHei;font-size: 20px;text-align:center;margin-top: 30px;">
<span class="glyphicon glyphicon-home"></span>Home
</a>
<font class="col-md-4 col-md-offset-2" style="font-family: SimHei;font-size: 30px;text-align:center;margin-top: 30px;">
<a href="/tools" style="cursor: pointer;">QiXiao - Chat</a>
</font>
</header>
<hr>
<article class="row">
<section class="col-md-10 col-md-offset-1" style="border:border:solid #4B5288 1px;padding:0">Admin : QiXiao </section>
<section class="col-md-10 col-md-offset-1 row" style="border:solid #4B5288 1px;padding:0">
<section class="col-md-9" style="height: 400px;">
<section class="row" style="height: 270px;">
<textarea class="form-control" style="width:100%;height: 100%;resize: none;overflow-x: none;overflow-y: scroll;" readonly="true" id="txt_view"></textarea>
</section>
<section class="row" style="height: 130px;border-top:solid #4B5288 1px; ">
<textarea class="form-control" style="overflow-y: scroll;overflow-x: none;resize: none;width: 100%;height:70%;border: #fff" id="txt_sub"></textarea>
<button class="btn btn-primary" style="float: right;margin: 0 5px 0 0" id="btn_sub">Submit</button>
</section>
</section>
<section class="col-md-3" style="height: 400px;border-left: solid #4B5288 1px;"></section>
</section>
</article>
</body>
</html>
-
【系统测试】
-
1、首先我们将我们的服务运行起来
-
2、调用测试