Metaweb queries through a proxy

[ permalink ] [ download ]
/**
 * metaweb_proxy.js: 
 *
 * This file implements a Metaweb.read() utility function using XMLHttpRequest
 * and a server-side proxy script named mqlread.php
 * For simplicity, this code requires a native XMLHttpRequest object,
 * which means that it does not work in Internet Explorer prior to IE7.
 **/
var Metaweb = {};                    // Define our namespace
Metaweb.QUERY_PROXY = "mqlread.php"; // The relative URL of the proxy service

// Send query q to Metaweb, and pass the result to function f.
// If hasEnvelope is omitted or false, then this function wraps an
// envelope around the query.
Metaweb.read = function(q, f) {
    // Put the query in inner and outer envelopes
    envelope = {qname: {query: q}}
    // Serialize the envelope to a JSON string
    var serialized = JSON.serialize(envelope);
    // URL encode the serialized query
    var encoded = encodeURIComponent(serialized);
    // Build the query URL
    var url = Metaweb.QUERY_PROXY + "?queries=" + encoded

    // Use XMLHttpRequest to submit the request to the proxy
    var request = new XMLHttpRequest();
    // When the response arrives, call this function
    request.onreadystatechange = function() {
        // If the request is done and was successful
        if (request.readyState == 4 && request.status == 200) {
            // Parse the JSON text of response to an envelope object
            var outerEnvelope = JSON.parse(request.responseText);
            // Get inner envelope from outer envelope
            var innerEnvelope = outerEnvelope.qname;
            // Make sure the query was successful
            if (innerEnvelope.status == "/mql/status/ok") {
                // Take the result object out of the response envelope
                var result = innerEnvelope.result;
                // And pass that object to the user's function
                f(result);
            }
        }
    }
    // Now send the request to the proxy
    request.open("GET", url);
    request.send(null);
};
hits counter