使用jQuery的XML到javascript数组

Jos*_*ker 10 javascript xml arrays ajax jquery

我是XML和AJAX的新手,我只是Javascript和jQuery的新手.在我设计我们的网站的其他工作职责.截止日期非常接近,我能想到的唯一方法是使用AJAX.我有一个充满XML对象的文档,比如这个重复:

<item>
    <subject></subject>
    <date></date>
    <thumb></thumb>
</item>
Run Code Online (Sandbox Code Playgroud)

我想创建一个包含所有元素及其子元素的数组.我已经阅读了几个小时的AJAX jQuery教程,甚至不知道从哪里开始,因为他们都假设一定程度的javascript熟练程度.如果有人能告诉我循环所有元素并将他们的孩子放入阵列的最简单方法,我会很感激.

mad*_*end 12

使用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
                })
            }  
        }); 
Run Code Online (Sandbox Code Playgroud)


Tro*_*sum 5

我写了这个..非常简单的方法来获取一个健康的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;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!!