在我的烧瓶应用程序中使用socketio,我想显示发件人的姓名和邮件,但此处只显示邮件,发件人的姓名只显示" [对象]你好&# 34;在浏览器中。
**# server.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config[ 'SECRET_KEY' ] = 'jsbcfsbfjefebw237u3gdbdc'
socketio = SocketIO( app )
@app.route( '/' )
def hello():
return render_template( './index.html' )
def messageRecived():
print( 'message was received!!!' )
@socketio.on( 'my event' )
def handle_my_custom_event( json ):
print( 'recived my event: ' + str( json ) )
socketio.emit( 'my response', json, callback=messageRecived )
if __name__ == '__main__':
socketio.run( app, debug = True )
**
<form action="" method="POST">
<b>Type your message below <span class="glyphicon glyphicon-arrow-down"></span></b>
<div class="clearfix" style="margin-top: 5px;"></div>
<div id="username">My Name</div>
<div style="padding-top: 5px;"></div>
<input type="text" class="message form-control" placeholder="Messages">
<div style="padding-top: 5px;"></div>
<button type="submit" class="btn btn-success btn-block"><span class="glyphicon glyphicon-send"></span> Send</button>
</form>
</div>
</div>
**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script>
var socket = io.connect( 'http://' + document.domain + ':' + location.port )
// broadcast a message
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
} )
var form = $( 'form' ).on( 'submit', function( e ) {
e.preventDefault()
let username = $( '#username' ).val()
let user_input = $( 'input.message' ).val()
socket.emit( 'my event', {
username : $("#username"),
message : user_input
} )
// empty the input field
$( 'input.message' ).val( '' ).focus()
} )
})
socket.on( 'my response', function( msg ) {
console.log( msg )
if( typeof msg.username !== 'undefined' ) {
$( 'h1' ).remove()
$( 'div.message_holder' ).append( '<div class="msg_bbl"><b style="color: #000">'+msg.username+'</b> '+msg.message+'</div>' )
}
} )
</script>**
答案 0 :(得分:0)
您正在向服务器发送DOM元素,而不是其内容。添加 socket.emit( 'my event', {
username : $("#username").text(),
message : user_input
} )
以获取实际用户名:
{{1}}