如何在JSON中格式化HTML字符串 前端POST提交返回400错误解决方法
问题原因
返回400错误的核心原因是手动拼接JSON字符串时没有对HTML内容里的特殊字符做转义,生成的JSON格式不符合规范,服务端无法正常解析就返回了400响应。你提交的HTML内容里包含双引号、换行符、制表符等特殊字符,直接拼接到JSON字符串中会直接破坏整体结构。
解决方法
不要手动拼接JSON字符串,直接使用JS原生的JSON.stringify()方法,它会自动处理所有需要转义的特殊字符,生成完全符合规范的JSON字符串。
修改后的完整代码
function saveContent(){ console.log("calling save content"); var html_content = document.getElementById("generated_html_textarea"); var xhr = new XMLHttpRequest(); xhr.open("POST", "/wordmatch", true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.onreadystatechange = function() { if(xhr.readyState == 4) { if(xhr.status == 201) { console.log("content saved"); } else{ console.log("content was not saved successfully, status code: " + xhr.status); } } } // 用JSON.stringify自动生成合法JSON const requestData = JSON.stringify({ content: html_content.value }); console.log(requestData); xhr.send(requestData); }
内容的提问来源于stack exchange,提问作者Evan Gertis
相关产品推荐
相关产品推荐

