Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consuming JSON data without jQuery (sans getJSON)

How can I consume a JSON document without jQuery? Instead of calling the method getJSON(), I'd like to design my own. How do I do that?

like image 819
VIVEK MISHRA Avatar asked Jul 13 '10 14:07

VIVEK MISHRA


People also ask

Is getJSON an Ajax call?

getJSON()) is an AJAX method that is used to fetch JSON data using HTTP GET request.

What is jQuery getJSON?

jQuery getJSON() Method The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

How do I post JSON data using JavaScript?

How do I post JSON data using JavaScript? To post data in JSON format using JavaScript/jQuery, you need to stringify your JavaScript object using the JSON. stringify() method and provide a Content-Type: application/json header with your request.

What does getJSON return?

getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.


1 Answers

If it's the same domain request then use window.XMLHttpRequest. If it's remote, then inject a script element, you can see how jQuery does it:

    // If we're requesting a remote document
    // and trying to load JSON or Script with a GET
    if ( s.dataType === "script" && type === "GET" && remote ) {
        var head = document.getElementsByTagName("head")[0] || document.documentElement;
        var script = document.createElement("script");
        script.src = s.url;
        if ( s.scriptCharset ) {
            script.charset = s.scriptCharset;
        }

        // Handle Script loading
        if ( !jsonp ) {
            var done = false;

            // Attach handlers for all browsers
            script.onload = script.onreadystatechange = function() {
                if ( !done && (!this.readyState ||
                        this.readyState === "loaded" || this.readyState === "complete") ) {
                    done = true;
                    success();
                    complete();

                    // Handle memory leak in IE
                    script.onload = script.onreadystatechange = null;
                    if ( head && script.parentNode ) {
                        head.removeChild( script );
                    }
                }
            };
        }

        // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
        // This arises when a base node is used (#2709 and #4378).
        head.insertBefore( script, head.firstChild );

        // We handle everything using the script element injection
        return undefined;
    }

Use a JSON Parser. You can also use eval but it's frowned upon in favor of a JSON parser.

Here's jQuery's internal parseJSON method:

parseJSON: function( data ) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim( data );

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
        .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {

        // Try to use the native JSON parser first
        return window.JSON && window.JSON.parse ?
            window.JSON.parse( data ) :
            (new Function("return " + data))();

    } else {
        jQuery.error( "Invalid JSON: " + data );
    }
},
like image 50
meder omuraliev Avatar answered Oct 05 '22 17:10

meder omuraliev