Como ler o conteúdo do arquivo xml em jQuery e mostrar em elementos html?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script src=Cloudtags.js></script>
<title>Css Globe: tag clouds</title>
<link rel="stylesheet" type="text/css" href="Cloudtags.css">
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div id="container">
<script type="text/javascript" src="http://cssglobe.com/ads/blogsponsor.js"></script>
<div id="side">
<div class="tags">
<ul class="cld">
<li class="tag1" id="java"><a href="https://www.google.com">google</a></li>
<li class="tag2"><a href="#">Chiessy</a></li>
<li class="tag3"><a href="#">sitemap</a></li>
<li class="tag2"><a href="#">Sales</a></li>
<li class="tag4" ><a href="#">Gohome</a></li>
<li class="tag1"id="temp"><a href="#">Movies</a></li>
<li class="tag1"><a href="#">It Jobz</a></li>
<li class="tag5"><a href="#">Alza</a></li>
<li class="tag2"><a href="#">Sea food</a></li>
<li class="tag1"><a href="#">Hospital</a></li>
<li class="tag3"><a href="#">Smart phone</a></li>
<li class="tag4"><a href="#">Pizza </a></li>
<li class="tag1"><a href="#">Aerobics</a></li>
<li class="tag5"><a href="#">Yahoo...</a></li>
<li class="tag1"><a href="#">Anti-Virus</a></li>
<li class="tag2"><a href="#">Travel</a></li>
</ul>
</div>
</div>
<div id="xmldata"></div>
</div><br>
</body>
</html>
E esta é a minha .ficheiro js:
$(document).ready(function() {
var nm;
$.ajax({
type: "GET" ,
url: "sampleXML.xml" ,
dataType: "xml" ,
success: function(xml) {
$(xml).find('person').each(function() {
nm= $(this).text()
$("#temp").html(nm);
}
}
});
});
O Meu ficheiro xml é o seguinte:
<?xml version='1.0' ?>
<doc>
<person>
<name>sachin</name>
<age>21</age>
</person>
<person>
<name>Akash</name>
<age>18</age>
</person>
</doc>
Mas isto não funciona. Preciso de ligar um ficheiro externo para"$.Forum" .
Por isso, por favor, diz-me onde estou a cometer erros . .
obrigado antecipadamente . .
7 answers
var xmlDoc = $.parseXML( xml );
var $xml = $(xmlDoc);
var $person = $xml.find("person");
$person.each(function(){
var name = $(this).find('name').text(),
age = $(this).find('age').text();
$("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');
});
Simplesmente você pode ler o ficheiro XML como dataType: "xml", ele irá reutilizar o objecto xml já processado. você pode usá-lo como objeto jquery e encontrar qualquer coisa ou loop jogá-lo...etc.
$(document).ready(function(){
$.ajax({
type: "GET" ,
url: "sampleXML.xml" ,
dataType: "xml" ,
success: function(xml) {
//var xmlDoc = $.parseXML( xml ); <------------------this line
//if single item
var person = $(xml).find('person').text();
//but if it's multible items then loop
$(xml).find('person').each(function(){
$("#temp").append('<li>' + $(this).text() + '</li>');
});
}
});
});
Em Primeiro Lugar, criar em Arquivo e, em seguida, converter os seus dados xml em array e recuperar esses dados no formato json para a resposta de sucesso ajax.
Tentar como em baixo:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "sample.php",
success: function (response) {
var obj = $.parseJSON(response);
for(var i=0;i<obj.length;i++){
// here you can add html through loop
}
}
});
});
Amostra.php
$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;
Pode usar $.each()
Suponha que o seu xml
é
<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>
Na tua Ajax
success
success: function (xml) {
$(xml).find('Cloudtags').each(function(){// your outer tag of xml
var id = $(this).find("id").text(); //
});
}
Para o seu caso
success: function (xml) {
$(xml).find('person').each(function(){// your outer tag of xml
var name = $(this).find("name").text(); //
var age = $(this).find("age").text();
});
}
O texto de resposta é o que procura. Exemplo:
$.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});
Onde o xml é o teu ficheiro. Lembre-se que este será o seu xml na forma de uma string. Você pode analisá-lo usando xmlparse como alguns deles mencionados.
$.get("/folder_name/filename.xml", function (xml) {
var xmlInnerhtml = xml.documentElement.innerHTML;
});
Obter o XML usando a chamada Ajax, encontrar o elemento principal, circular por todo o elemento e adicionar dados na tabela.
Código da amostra
//ajax call to load XML and parse it
$.ajax({
type: 'GET',
url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml', // The file path.
dataType: 'xml',
success: function(xml) {
//find all book tags, loop them and append to table body
$(xml).find('book').each(function() {
// Append new data to the tbody element.
$('#tableBody').append(
'<tr>' +
'<td>' +
$(this).find('author').text() + '</td> ' +
'<td>' +
$(this).find('title').text() + '</td> ' +
'<td>' +
$(this).find('genre').text() + '</td> ' +
'<td>' +
$(this).find('price').text() + '</td> ' +
'<td>' +
$(this).find('description').text() + '</td> ' +
'</tr>');
});
}
});
Ligação de violino: https://jsfiddle.net/pn9xs8hf/2/