基本上我想打印一个api列表,但是我不确定我是否正确使用了模板文字
<h6>XMLHttpRequest</h6>
<ul class="testing"></ul>
html
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){
if(xhr.status == 200){
var text = JSON.parse(xhr.responseText)
document.getElementsByClassName('testing')[0].textContent =
`<li>User id: ${text.userId}</li>
<li>Title: ${text.title}</li>
`;
}
}
}
var url = "https://jsonplaceholder.typicode.com/posts/1";
xhr.open('GET', url, true)
xhr.send()
我有种感觉,我的模板字面意思有误。我需要指导大声笑
<li>User id: 1</li> <li>Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit</li>
这是我的输出,但是我希望它以列表格式减去标签大声笑
答案 0 :(得分:1)
使用innerHTML
代替textContent
:
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
const responseObj = JSON.parse(xhr.responseText)
document.querySelector('.testing').innerHTML =
`<li>User id: ${responseObj.userId}</li>
<li>Title: ${responseObj.title}</li>
`;
}
}
}
const url = "https://jsonplaceholder.typicode.com/posts/1";
xhr.open('GET', url)
xhr.send()
<h6>XMLHttpRequest</h6>
<ul class="testing"></ul>