textarea无法正常显示MySQL存储的换行内容问题求助
I ran into a similar issue before, so let's break down what's happening and fix it step by step.
The core problem here is that after parsing the AJAX response, edit_data.name contains literal \n strings (two characters: backslash + 'n') instead of actual newline control characters (\n, a single character). That's why your textarea shows a\nb instead of two separate lines.
Even though you said the AJAX response matches your hardcoded JSON string, there's likely a double-escaping issue happening on the backend—let's cover both frontend and backend fixes:
Fix 1: Frontend String Replacement (Quick Fix)
Before assigning the value to the textarea, replace all literal \n sequences with actual newlines using a regex:
success : function(data, status){ var edit_data = JSON.parse(data); // Replace literal \n with actual newline characters var formattedName = edit_data.name.replace(/\\n/g, '\n'); $('#mdl_update_team_order').val(edit_data.order_no); $('#mdl_update_team_team').val(edit_data.team); $('#mdl_update_team_names').val(formattedName); // Use the formatted value }
The regex /\\n/g globally matches every instance of the literal \n and swaps it for a real newline control character, which the textarea will render correctly.
Fix 2: Fix Backend JSON Output (Root Cause Solution)
Frontend replacement is a band-aid—better to fix the issue at the source in your teams_post.php file:
Check for double escaping: If you're using functions like
addslashes()on your database data before encoding to JSON, remove them.json_encode()automatically handles escaping special characters like newlines, so extra escaping will cause double-encoded\\nsequences.Example of correct PHP code:
// Fetch record from MySQL $editID = $_POST['editID']; $stmt = $pdo->prepare("SELECT * FROM teams WHERE id = ?"); $stmt->execute([$editID]); $record = $stmt->fetch(PDO::FETCH_ASSOC); // Directly encode to JSON—no extra escaping needed echo json_encode($record); exit;If your database stores literal
\nstrings: If your MySQL data has actual\ncharacters (not newlines), replace them before encoding:$record['name'] = str_replace('\\n', "\n", $record['name']); echo json_encode($record); exit;
How to Verify the Issue
To confirm what's really in your parsed data, add a console.log in your AJAX success function:
success : function(data, status){ var edit_data = JSON.parse(data); console.log(edit_data.name); // Check the output in your browser's dev tools }
- If the console shows
a\nb(with a visible backslash), you need the replacement fix. - If it shows
aon one line andbon the next, the issue is elsewhere—but your manual test rules that out.
内容的提问来源于stack exchange,提问作者Thillai Manalan Thallai Muthu

