我试图使用JavaScript显示图像但图像不显示。我使用ajax获取数据,然后在显示图像之前将图像的值附加到URL。将图像附加到URL后我检查控制台,我可以看到图像的URL是正确的,指向图像。我甚至可以从控制台复制URL并将其粘贴到浏览器上,图像显示效果很好。但是,当我将url追加到img2.appendChild(image)时,图像不会显示;
const URL="http://test/somtest?random=random";
const url="Http://test/document/img/";
function getdata() {
let xhr = new XMLHttpRequest();
let img2 = document.getElementById("image");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
var image = document.createElement("img");
image.src=url+data.image;
console.log(image);
while (img2.firstChild) {
img2.removeChild(img2.firstChild);
}
img2.appendChild(image);
}
}
xhr.open('GET', URL);
xhr.send();
}
图像不能有子节点,请尝试这样做:
const URL="http://test/somtest?random=random";
const url="Http://test/document/img/";
function getdata() {
let xhr = new XMLHttpRequest();
let img2 = document.getElementById("image");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
img2.src=url+data.image;
}
}
xhr.open('GET', URL);
xhr.send();
}
顺便说一句,如果你使用的是现代浏览器(不是IE),请查看fetch API
我通过添加图像属性,高和宽度来解决它
const URL="http://test/somtest?random=random";
const url="Http://test/document/img/";
function getdata() {
let xhr = new XMLHttpRequest();
let img2 = document.getElementById("image");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
var image = document.createElement("img");
image.src=url+data.image;
image.height = 100;
image.width = 100;
img2.appendChild(image);
}
}
xhr.open('GET', URL);
xhr.send();
}