问题描述
在获取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);
});
```