onsdag 26 juni 2013

How to use selectSingleNode/selectNodes/xpath with ajax-returned xml document in jQuery and ie9/ie10

Think I spent a day reading of how to be able to use the returned xml when doing a $.get/$.ajax with jQuery. The solution was first of all to use a new version of jQuery, if I understood it correctly they do not return the browser-parsed xml-document anymore (http://bugs.jquery.com/ticket/13276). They always convert the xml internally using the parseXML method. (jQuery v. 1.9.1)

Problem now was that the parseXML method doesn't take ie9/ie10 into consideration. This is the new parseXML that I concocted. The problem that now arose was that the converter method was still pointing to the old parseXML method so I had to add a few more lines updating the converters object.

If you know of a better solution please comment below.


$.parseXML = function ( data ) {
    var xml, tmp;
    if ( !data || typeof data !== "string" ) {
        return null;
    }
    try {
        if ( window.DOMParser && navigator.userAgent.indexOf("MSIE 9") == -1 && navigator.userAgent.indexOf("MSIE 10") == -1) { // Standard
            tmp = new DOMParser();
            xml = tmp.parseFromString( data , "text/xml" );
        } else { // IE
            xml = new ActiveXObject( "Microsoft.XMLDOM" );
            xml.async = "false";
            xml.loadXML( data );
        }
    } catch( e ) {
        xml = undefined;
    }
    if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
        jQuery.error( "Invalid XML: " + data );
    }
    return xml;
}
$.ajaxSetup({
 converters:{"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": $.parseXML}
})

Inga kommentarer:

Skicka en kommentar