I am trying to display image using javascript but the image is not displaying. I have used ajax to get data and then append the value of the image to a URL before display the image. after appending the image to URL I check the console, I can see that the URL of the image is correct which is pointing to the image. I can even copy the URL from the console and paste it on the browser and the image display well. However, the image is not displaying when i append the url to 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();
}
答案 0 :(得分:0)
Images can't have child nodes, try this instead:
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();
}
BTW, if you are using modern browsers (not IE) check the fetch API
答案 1 :(得分:0)
I fix it by adding the image properties, the hight, and the width
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();
}