将文本/字符串响应转换为html

问题描述

获取POST消息中,我收到了纯文本格式的html响应。我想选择相关部分,然后将其显示在我的网页中,所以我在做:

 document.querySelector('form').onsubmit = (event) => {
    event.preventDefault();

  fetch("",{

    method: 'POST',body: JSON.stringify({
      body: document.querySelector('#new_message').value
    }),headers: {
      "Content-type": "application/json; charset=UTF-8","X-CSrftoken": getCookie('csrftoken')
    }
  })
  .then(response => response.text())
  .then(result => {
    document.querySelector('#new_message').value = ""
    let div = document.createElement('div')
 
    fetch("",{
      headers: {
        "Content-type": "charset=UTF-8",}
    })
    .then(response => response.text())
    .then(result2 => {

        var success = $(result2).filter("#granpost"+result['id']); 
        div.append(success);

        document.querySelector('#plis').append(div);
        console.log(success); // div#success  
    });



  });

}

这是我要执行的代码: 首先,将字符串转换为html,然后获取id为"granpost"+result['id']的div并将其存储在success变量中。最后,在我的页面显示success div。

这不起作用,在我的页面上唯一显示内容是:“ [object Object]”

console.log返回以下内容m.fn.init [prevObject: m.fn.init(45),context: undefined]

解决方法

第一个问题,响应是一个字符串,您将其用作对象。看起来像

.then(response => response.text())
.then(result => {})

应该使用json

.then(response => response.json())
.then(result => {})

现在输出:

您正在混合使用DOM和jQuery。因此,您要将jQuery对象附加到DOM元素。因此,为什么要引用HTML中的对象。更改

let div = document.createElement('div')

const div = $('<div></div>')

然后改变

document.querySelector('#plis').append(div);

$('#plis').append(div);

您还使用带有ID的过滤器。过滤器正在从其具有的层次上运行元素。并且由于它是一个id,所以我假设您有一个。因此,您应该使用find。

var success = $(result2).find("#granpost"+result['id']); 
,

另一种解决方案: 将此获取的父级响应更改为.json(),然后:

fetch("",{
      headers: {
        "Content-type": "charset=UTF-8",}
    })
    .then(response => response.text())
    .then(result2 => {


        var doc = new DOMParser().parseFromString(result2,"text/html");

        je = doc.querySelector(`#granpost${result['id']}`)


        div.append(je);

        $('#plis').append(div);
    });
```

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...