Monday, July 13, 2015

AJAX dengan JavaScript Mentah

Mendapatkan konten dari dokumen HTML yang lain pada domain yang sama tanpa menggunakan jQuery.

/**
 * Get data from a URL
 * @param  {String} url        The URL to get
 * @param  {Function} success  Callback to run on success
 * @param  {Function} error    Callback to run on error
 */

var getURL = function(url, success, error) {
    // Feature detection
    if (!window.XMLHttpRequest) return;
    // Create new request
    var request = new XMLHttpRequest();
    // Setup callbacks
    request.onreadystatechange = function() {
        // If the request is complete
        if (request.readyState === 4) {
            // If the request failed
            if (request.status !== 200) {
                if (error && typeof error === "function") {
                    error(request.responseText, request);
                }
                return;
            }
            // If the request succeeded
            if (success && typeof success === "function") {
                success(request.responseText, request);
            }
        }
    };
    // Get the HTML
    request.open('GET', url);
    request.send();
};

Penggunaan

Dasar:

getURL(
    '/about',
    function(data) {
        // On success…
    },
    function(data) {
        // On failure…
    }
);

Cari elemen spesifik pada halaman yang dipanggil dan masukkan kontennya ke dalam elemen tertentu pada halaman saat ini:

getURL(
    '/about',
    function(data) {
        // Create a `<div>` and inject the HTML into it
        var div = document.createElement(div);
        div.innerHTML = data;
        // Find the element you’re looking for in the `<div>`
        var from = div.querySelector('#some-element');
        var to = document.querySelector('#another-element');
        // Quit if the element or the place where you want to inject it doesn’t exist
        if (!from || !to) return;
        // Inject the element into the DOM
        to.innerHTML = from.innerHTML;
    }
);

Referensi: Making AJAX Requests with Native JavaScript

Labels: , ,