简体   繁体   中英

How to parse XML response from API in JavaScript?

I am working with this API , which returns flight statuses originating in LHR to MAN (just an example). The response is formatted as XML, but I'm having trouble reading it with JavaScript.

I tried the following:

function loadXMLDoc(dname) { //the dname here is the url
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
}

But it doesn't work. Is there another way to read the XML response of the API?

You could use jQuery and then make your ajax call using jQuery.ajax()

The code might look something like this...

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: url,
        data: JSON.stringify(data),
        dataType: "json",
        error: function (response) {
            alert('Error: There was a problem processing your request, please refresh the browser and try again');
        },
        success: function (response) {
            if (response !== undefined && response !== null) {
               /* Evaluate the SOAP response object here */
            }
        }
    });

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