Использование данных JSON без jQuery (без getJSON) - PullRequest
9 голосов
/ 13 июля 2010

Как я могу использовать документ JSON без jQuery?Вместо того, чтобы вызывать метод getJSON(), я бы хотел разработать свой собственный.Как мне это сделать?

Ответы [ 2 ]

15 голосов
/ 13 июля 2010

Если это тот же запрос домена, используйте window.XMLHttpRequest.Если он удаленный, вставьте элемент скрипта, вы можете увидеть, как это делает jQuery:

    // 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;
    }

Использовать JSON Parser .Вы также можете использовать eval, но он не одобряется в пользу парсера JSON.

Вот внутренний метод jQuery parseJSON:

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 );
    }
},
3 голосов
/ 13 июля 2010

Вы должны будете свернуть свою собственную функцию JSON / AJAX.Вот несколько примеров здесь .Я не уверен, насколько они хороши.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...