XML-массив javascript с jQuery
Я новичок в XML и AJAX, и я только новичок в Javascript и jQuery. Среди других должностных обязанностей я проектирую наш сайт. Крайний срок очень близок, и единственный способ, которым я могу придумать этот проект, - это AJAX. У меня есть документ, полный XML-объектов, таких как повторяющийся:
<item>
<subject></subject>
<date></date>
<thumb></thumb>
</item>
Я хочу создать массив из всех элементов и их дочерних элементов. Я читал jQuery tutorials на AJAX в течение нескольких часов и даже не знаю, с чего начать, потому что все они предполагают определенный уровень владения javascript. Если бы кто-нибудь мог показать мне самый простой способ перебросить все элементы и поместить своих детей в массив, я был бы признателен, если бы он был тонким.
Ответы
Ответ 1
Используя jQuery, $.ajax()
ваш XML файл и при успешном завершении получения данных с помощью each
, например:
var tmpSubject, tmpDate, tmpThumb;
$.ajax({
url: '/your_file.xml',
type: 'GET',
dataType: 'xml',
success: function(returnedXMLResponse){
$('item', returnedXMLResponse).each(function(){
tmpSubject = $('subject', this).text();
tmpDate = $('date', this).text();
tmpThumb = $('thumb', this).text();
//Here you can do anything you want with those temporary
//variables, e.g. put them in some place in your html document
//or store them in an associative array
})
}
});
Ответ 2
Я написал это.. довольно простой способ взять приветственный XML-ответ/строку и проанализировать его с помощью jquery, а затем преобразовать в массив.
var response = '<?xml version="1.0" encoding="UTF-8"?><root><node1>something</node1></root>
var xmlDoc = $.parseXML( response );
var myArray = getXMLToArray(xmlDoc);
alert(myArray['root']['node1']);
//Pop up window displaying the text "something"
function getXMLToArray(xmlDoc){
var thisArray = new Array();
//Check XML doc
if($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner array
var NextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = $(xmlDoc).find(this.nodeName).text();
}
});
}
return thisArray;
}
Надеюсь, это поможет!
Ответ 3
Если вы используете jQuery, то parseXML будет всасывать весь XML-документ в полезную структуру данных.
Ответ 4
Я добавил в ваш script Troublesum
function getXMLToArray(xmlDoc){
var thisArray = new Array();
//Check XML doc
if($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner array
var NextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = [];
$(xmlDoc).children(this.nodeName).each(function(){
thisArray[this.nodeName].push($(this).text());
});
}
});
}
return thisArray;
}
Теперь он также поддерживает много детей с одинаковым именем в XML. f.e
XML
<countries>
<NL>
<borders>
<country>Germany</country>
<country>Belgium</country>
countries.NL.borders [1] предоставит Германии.