小弟近日接触flask框架的socketio模块,用以下代码测试了下效果,发现字符串信息能够从服务器异步加载到客户端并显示在网页上,但是换成json类型的就不行,浏览器会报错
Uncaught TypeError: Cannot read property 'num' of undefined
说是属性没有定义,不知怎么解决,请各位大侠帮忙看下,代码如下:
服务器端:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('my event', namespace='/test')
def handle_my_custom_event(message):
print 'receive'
emit('connect', {'num': 5, 'kind': 'apple', 'message': message['data']})
if __name__ == '__main__':
socketio.run(app)
客户端网页:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>flask-socketio</title>
</head>
<body>
<h1>Hello World</h1>
<p><span>Only <span id="count"></span>
left in stock! Order 123now!</span></p>
</body>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var namespace = '/test'
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function(msg) {
$('#count').html(msg.num)});
function a(){socket.emit('my event', {data: 'I\'m connected!'})};
setTimeout(a, 3000);
</script>
</html>
将字符串转换为json啊………………………