Hướng dẫn xmlhttprequest nodejs

Reset

Click Me

xhr-example.js


function clickHandler[evt] {
    var URL= "//ex1.o7planning.com/_testdatas_/simple-xml-data.xml";
    // var URL= "//ex1.o7planning.com/_testdatas_/triceratops.png";
    resetLog[];

    // Create XMLHttpRequest.
    let xhr = new XMLHttpRequest[]; 
    appendLog["URL: " + URL];
    appendLog["\n\n"];

    xhr.onprogress = function[progressEvent] {
        appendLog["onprogress! " + progressEvent];
    }
    // readyState [State of request]:
    // 0 - XMLHttpRequest.UNSENT
    // 1 - XMLHttpRequest.OPENED
    // 2 - XMLHttpRequest.HEADERS_RECEIVED
    // 3 - XMLHttpRequest.LOADING
    // 4 - XMLHttpRequest.DONE
    xhr.onreadystatechange = function[event]  {
        appendLog["onreadystatechange! readyState = " + xhr.readyState];
        appendLog[" status = " + xhr.status];
        appendLog[" statusText = " + xhr.statusText];
    }
    xhr.onload = function[progressEvent] {
        appendLog["onload!"];
        appendLog[" status = " + xhr.status];
        appendLog[" statusText = " + xhr.statusText];
        
        appendLog[" ------ xhr.responseText ------: "];
        appendLog[xhr.responseText];

        appendLog[" ------ xhr.responseXML -------: "];
        appendLog[xhr.responseXML]; // [object XMLDocument]

        // Convert XMLDocument to String.
        var xmlString = [new XMLSerializer[]].serializeToString[xhr.responseXML];
        appendLog[xmlString];
    } 
    xhr.onerror = function[progressEvent] {
        appendLog["onerror!"];
        appendLog["Has Error!"];
    }
    let async = true;
    // Initialize It.
    xhr.open["GET", URL, async];

    // Send it [Without body data]
    xhr.send[];
}
function resetLog[] {
    document.getElementById['textarea-log'].value = "";
}
function appendLog[msg] {
    document.getElementById['textarea-log'].value += "\n" + msg;
}

Trong ví dụ trên tôi không đề cập tới cách làm thế nào để phân tích nội dung XML [XMLDocument], nếu bạn quan tâm có thể tham khảo các bài viết khác dưới đây:

Chủ Đề