简体   繁体   中英

Can a javascript object containing xml data be parsed using the jquery .ajax() call?

I have a javascript object containing the xml data in that. I want to parse this object inside the .ajax() call in the jquery. Does anyone know how to do it? I am struggling for the pointer. Please help me with this.

Thanks!

Use jQuery.parseXML( data );

See docs here: http://api.jquery.com/jQuery.parseXML/

Here's an example of parsing a catalog of books contained in book tags and caching results into a javascript object for much easier access to data later on. XML Sample taken from MSDN site

This allows a lot easier data access later in than having to parse the xml again to look for results. The format of the store object can be set to best suit needs of the app this way also.

DEMO : http://jsfiddle.net/WpFUE/

var xmlResults = {};

$(xml).find('book').each(function() {
    var $book = $(this);
    var id = $book.attr('id');
    var title = $book.find('title').text();
    var auth = $book.find('author').text();
    var descrip = $book.find('description').text();
    /* store data in object with id for key */
    xmlResults[id] = {
        author: auth
    }

    $('body').append('<div class="book_wrap" data-id="' + id + '">Book: ' + title + '<br>' + descrip + '<p>CLICK ANYEHWERE ON DIV TO GET AUTHOR</div>')

})

$('.book_wrap').click(function() {
    var id = $(this).data('id');
    /* no parsing of xml, use simple javascript object notation to referece data stored*/
    var auth = xmlResults[id].author;
    alert('Author is '+auth)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM