![](/img/trans.png)
[英]Parse XML data on page load & insert into div using AJAX / Javascript
[英]using ajax request to get xml data and make javascript load image
我正在使用ajax请求从服务器加载数据。 一个php文件表示一个xml文件。 我成功获取了所有数据,但无法在屏幕上获取图像。
在下面的for ...循环代码中,我做了一些评论。 有人可以解释一下我如何使脚本加载图片,然后使用javascript动态添加。
使用appendChild将valIMG添加到按钮的底部。
function updatePlaneten(){
var valDiv, planets , valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for(var i=0;i<planets.length;i++){
(function(num){
valDiv = document.createElement("div");
valDiv.setAttribute("class", "divPresentPlanet" );
// I try to add an img element here.
// the variable imagename containts the path to the img: 'images/moon.jpg'
// appending it does add it to the div, tho the image isnt loaded
var valIMG = document.createElement("image");
var imagename = planets[num].getElementsByTagName("img")[0].childNodes[0].nodeValue;
valIMG.setAttribute("src", imagename );
valIMG.setAttribute("class", "IMGTAGPresentPlanet" );
// Get the id and the name from the xml info in current <planet> tag
var IDplanet = (planets[num].getElementsByTagName("id")[0].childNodes[0].nodeValue)-1;
var id = planets[num].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
var name = planets[num].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
var img = planets[num].getElementsByTagName("img")[0].childNodes[0].nodeValue + "<br>";
valDiv.innerHTML = id+"<br>"+name+"<br>"+ img +"<br>";
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = num;
valButton.object = this;
// FIX: PASS showinfo TO AN ANONYMOUS FUNCTION CONTAINING THE OBJECT
valButton.addEventListener('click', function(){
showinfo(valButton, planets, IDplanet);
});
// Place the button on screen
valDiv.appendChild(valButton);
valDiv.appendChild(valIMG);
// place img tag on screen
valDiv.appendChild(valIMG);
document.getElementById("planetenID").appendChild(valDiv);
}(i));
}
}
您的图片路径应相对于您的域是绝对的或相对的,例如'/images/moon.jpg'
,这意味着您有一些URL yourdomain.com/something
,如果您输入src="image/moon.jpg"
,则您的URL不正确src="image/moon.jpg"
。
创建您应该拥有的img元素的最佳JavaScript代码是什么
document.createElement('img')
insteand document.createElement('image')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.