使用XML中的AJAX显示图像

时间:2018-11-26 16:29:26

标签: javascript ajax xml

我正在学习AJAX,正在尝试从XML联系人调用图像并将其显示在表格中。

XML联系人如下:

<contact>
  <name>xxx xxx</name>
  <post>xxx xxx</post>
  <company>xxx</company>
  <address>xxx</address>

  <telephone>xxx</telephone>
  <mobile>xxx</mobile>

  <email>xx@xxx</email>
  <photo>img/xxx.jpg</photo>
</contact>

下面我称之为Ajax的是:

function myFunction(xml) {
        var i;
        var xmlDoc = xml.responseXML;
        var table = "<tr><th>Name</th><th>Post</th><th>Company</th><th>Address</th><th>Telephone</th><th>Mobile</th><th>Email</th><th>Photo</th></tr>";
        var x = xmlDoc.getElementsByTagName("contact");
        for (i = 0; i < x.length; i++) {
          table += "<tr><td>" +
            x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("post")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("company")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("address")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("telephone")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("mobile")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("email")[0].childNodes[0].nodeValue +
            "</td><td>" + 
            x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue +
            "</td></tr>";
        }

当前该表显示带有Photo标签,但仅显示文本“ img / xxx.jpg”,而不是我希望它显示实际图像。

1 个答案:

答案 0 :(得分:1)

您需要实现<img>标签,否则(您已经发现)否则,您要做的就是显示路径。

尝试在末尾替换以下行...

        "</td><td>" + 
        x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue +
        "</td></tr>";

有...

        "</td><td><img src='" + 
        x[i].getElementsByTagName("photo")[0].childNodes[0].nodeValue +
        "'/></td></tr>";
相关问题