【问题标题】:How can I display the content of an xml file in html divs with ajax call?如何使用 ajax 调用在 html div 中显示 xml 文件的内容?
【发布时间】:2019-06-17 00:53:06
【问题描述】:
我正在开发一个用于联系人管理的在线网站,我需要在 html div 中显示一个 xml 文件中的联系人。我怎样才能完全使用 AJAX CALL 来做到这一点?我的 xml 看起来像这样,我想把这个标签放在一些 div 中,每个联系人一个 div。
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<contact id_contact="1">
<firstName>Lara</firstName>
<lastName>Adey</lastName>
<photo>lara.png</photo>
<email>lara.adey@gmail.com</email>
<birthday>1999-03-12</birthday>
<adress>Brooklyn 99</adress>
<description>Nice girl</description>
<phone>520-447-9821</phone>
<interests>Coding</interests>
<idUser>2</idUser>
</contact>
</contacts>
【问题讨论】:
标签:
html
ajax
xml
call
display
【解决方案1】:
使用 JQuery $.ajax 在您的 javascript 中尝试此操作
文档:http://api.jquery.com/jquery.ajax/
$(document).ready(function () {
$.ajax({
type: "GET",
url: "contacts.xml",
dataType: "xml",
success: xmlParse
});
});
function xmlParse(xml) {
$(xml).find("contact").each(function () {
$(".main").append('<div class="contact"><div class="firstname">' + $(this).find("firstName").text() + '</div><div class="lastName">' + $(this).find("lastName").text() + '</div><div class="photo">Photo ' +
$(this).find("photo").text() + '</div><div class="email">Email ' + $(this).find("email").text() +'</div><div class="birthday">Birthday ' + $(this).find("birthday").text() + '</div><div class="address">Address ' + $(this).find("address").text() + '</div><div class="description">Description ' + $(this).find("description").text() + '</div><div class="phone">Phone ' + $(this).find("phone").text() + '</div><div class="interests">Interests ' +
$(this).find("interests").text() + '</div><div class="idUser">User ID ' +
$(this).find("idUser").text() + '</div></div>');
$(".contact").fadeIn(1000);
});
}
在您的 HTML 中:
<div class="main"></div>