XML to javascript array with jQuery

前端 未结 4 1579
面向向阳花
面向向阳花 2021-01-11 18:50

I am new to XML and AJAX and am only a newcomer to Javascript and jQuery. Among other job duties I design our website. A deadline is very near, and the only way I can think

4条回答
  •  感动是毒
    2021-01-11 19:37

    I wrote this.. pretty simple way to take a welformed XML response/string and parse it with jquery and then convert to array.

    var response = 'something'  
    
    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;
    }
    

    Hope this helps!!

提交回复
热议问题