代码之家  ›  专栏  ›  技术社区  ›  Evan Gertis

如何在json中格式化html字符串

  •  0
  • Evan Gertis  · 技术社区  · 4 年前

    预期 调用saveContent方法。textarea元素的值被连接成字符串。此字符串是发送到服务器的json。请求完成后,将返回201响应。

    真实的 调用saveContent方法。textarea元素的值被连接成字符串。此字符串是发送到服务器的json。回复为400。

    {"content":"<div id="maincontentstyle">
        <center>
            <div id="boxstyle">
                <h3 id="title">title</h3>
                    <center>
                        <div class="source">
                            <div id="s1" class="draggyBox-small">
                                k1
                            </div>
                            <div id="s2" class="draggyBox-small">
                                k2
                            </div>
                        </div>
                        </center>
                        <table id="tablestyle">
                            <tr>
                            <td id="row1">
                                <div id="t1" class="ltarget"></div>
                            </td >
                            <td id="d1">
                                d1
                                </td >
                            </tr>
                            <tr>
                            <td id="row2">
                                <div id="t2" class="ltarget"></div>
                            </td >
                            <td id="d2">
                                d2
                                </td >
                            </tr>
                        </table>
                    </center>
            </div>
        </center>
    </div>"}
    

    这是saveContent方法

    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 && xhr.status == 201) {
                    console.log("content saved");
                }
                else{
                    console.log("content was not save successfully");
                }
            }
            console.log('{"content":\"'
                    +html_content.value+'\"}');
            xhr.send('{"content":\"'
                    +html_content.value+'\"}');
        }
    
    1 回复  |  直到 4 年前
        1
  •  4
  •   Barmar    4 年前

    不要通过连接字符串来创建JSON。您没有正确地转义所有嵌套引号,将换行符转换为 \n

    使用 JSON.stringify()

    xhr.send(JSON.stringify({content: html_content.value}));