Python3+Flask/SocketIO实现无刷新页面更新HTML内容的方法
Hey there! I see exactly what's going on here—your submitted form data is showing up as plain text HTML tags instead of rendered interactive elements. Let's break down why this happens and fix it quickly.
The Root Issue
In your client-side JavaScript, you're using the text() method when processing the SocketIO response:
socket.on('my_response', function(msg) { $('#log').append('<br>' + $('<div/>').text('<input type="text" value="' + msg.data + '">').html()); });
The text() method’s job is to escape all HTML special characters (like < and >) into plain text. That’s why your <input> tag is displaying as a string instead of a functional input box.
Simple Fixes
You need to skip the escaping step and insert the HTML directly into the DOM. Here are two straightforward approaches:
Option 1: Directly Append HTML String
Modify your SocketIO handler to add the HTML content without escaping it:
socket.on('my_response', function(msg) { // Build your HTML element with dynamic data const htmlElement = `<br><input type="text" value="${msg.data}">`; // Append it to the log area $('#log').append(htmlElement); });
Option 2: Build Elements with jQuery (Cleaner for Complex Content)
If you prefer building elements programmatically (to avoid syntax errors), use jQuery to create the input element directly:
socket.on('my_response', function(msg) { // Create a new input element with your data const inputField = $('<input>').attr({ type: 'text', value: msg.data }); // Add a line break and the input to the log $('#log').append('<br>').append(inputField); });
Bonus: Rendering Full HTML Structures (Like Forms)
Since your end goal is a queue review system with full form elements, you can even send complete HTML snippets from your Flask backend. Here's how:
Update your Flask route to return the full form HTML:
@socketio.on('my_event', namespace='/test') def test_message(message): # Build the complete form with submitted data review_form = f''' <form class="review-form"> <input type="text" value="Recently added: {message['data']} {message['password']}"> <input type="submit" value="Approve"> </form> ''' emit('my_response', {'data': review_form})
Then in your client-side JS, just append the received HTML directly:
socket.on('my_response', function(msg) { $('#log').append('<br>' + msg.data); });
Quick Security Note
If this app will handle input from untrusted users, be careful with direct HTML insertion—it can expose you to XSS attacks. For public-facing apps, consider sanitizing user input before rendering it as HTML.
内容的提问来源于stack exchange,提问作者Swift

