How can I set JSON into a variable from a local url

时间:2022-09-09 23:21:32

Evidently jQuery has made me dumb.

显然jQuery让我愚蠢。

I've got a local url that serves up raw JSON, and I can't figure out how to consume that json from within my method without using jQuery.

我有一个提供原始JSON的本地URL,我无法弄清楚如何在不使用jQuery的情况下从我的方法中使用json。

Here's how I know to do it WITH jQuery

这是我用jQuery做的知道

var myJson;
$.getJSON('/local/path/to/json', function (data) { 
    myJson = data; 
});

// Now I can use myJson in a method.

3 个解决方案

#1


5  

To retrieve the JSON string from a server use XMLHttpRequest object as described in this reference:

要从服务器检索JSON字符串,请使用XMLHttpRequest对象,如本参考中所述:

http://developer.mozilla.org/en/XMLHttpRequest

You'll find that it's quite involved with all the unseen things you need to account and check for. Thus libraries like jQuery.

你会发现它完全涉及你需要考虑和检查的所有看不见的东西。因此像jQuery这样的库。

To convert the JSON string to a javascript object, use JSON.parse(). Here's the reference:

要将JSON字符串转换为javascript对象,请使用JSON.parse()。这是参考:

http://developer.mozilla.org/En/Using_native_JSON

Here's an example:

这是一个例子:

function readJSON(file) {
    var request = new XMLHttpRequest();
    request.open('GET', file, false);
    request.send(null);
    if (request.status == 200)
        return request.responseText;
};

var myObject = JSON.parse(readJSON('/local/path/to/json'));

EDIT #2: Thanks for editing in this example, Chase. A word of warning. It is not a good idea to make the open() method a synchronous call by using false in the 3rd parm. AJAX is intentionally designed for asynchronous use, and to make a synchronous call invites lock ups. As one who used to think there was a place for synchronous calls, I now find there's always a better way to get it done asynchronously. Word to the wise.

编辑#2:感谢在这个例子中编辑,Chase。一句警告。通过在第3个参数中使用false来使open()方法成为同步调用并不是一个好主意。 AJAX是专门为异步使用而设计的,并且使同步调用可以锁定。作为曾经认为有同步调用的地方的人,我现在发现总是有一种更好的方法来异步完成它。说到明智的话。

#2


1  

Please have a look at be below code snap which will on in all browsers, thanks

请看下面的代码快照,它将在所有浏览器中显示,谢谢

    function getJSONData(jsonurl) {
        var req = null;
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) { }
            }
        }
        req.open('GET', jsonurl, false);
        req.send(null);
        return req.status == 200 ? req.responseText : 'Error occurred';
    }
    var jsonData = JSON.parse(getJSONData('/local/path/to/json'));
    alert(getJSONData('/local/path/to/json'));

Hope this will be very helpful, thanks for your time

希望这对你的时间非常有帮助

#3


1  

I you're familiar with jQuery, this is a drop-in replacement for $.ajax:

我熟悉jQuery,这是$ .ajax的替代品:

Script:

function ajax( uri, settings ) {
    var ajax = new window.XMLHttpRequest(),
        data = settings.type == 'GET' ? '' : settings.data,
        async = settings.async ? settings.async : false;
        uri = settings.type == 'GET' ? uri + ( settings.data ? '?' + settings.data : '' ) : uri;

    ajax.onreadystatechange = function () {
        if ( ajax.readyState == 4 ) { //response ready
            if ( ajax.status == 200 ) { //success
                if ( settings.success ) settings.success( ajax.responseText, ajax.statusText );
                if ( settings.complete ) settings.complete( ajax, ajax.statusText );
            } else {
                if ( settings.error ) settings.error( ajax, ajax.status, ajax.statusText );
            };
        };
    };

    ajax.open( settings.type, uri, async );

    if ( settings.headers ) {
        for ( var header in settings.headers ) {
            ajax.setRequestHeader( header, settings.headers[header] );
        };
    };

    ajax.send( data );
};

Call it just like jQuery:

像jQuery一样调用它:

ajax( '/local/path/to/json', {
    "type": "GET", //or "POST"
    //"data": "<query string>", //if POST
    "success": function ( data, status ) {
        var myJson = window.JSON.parse( data );
    },
    "error": function ( response, status, error ) {
        // handle error
    }
} );

#1


5  

To retrieve the JSON string from a server use XMLHttpRequest object as described in this reference:

要从服务器检索JSON字符串,请使用XMLHttpRequest对象,如本参考中所述:

http://developer.mozilla.org/en/XMLHttpRequest

You'll find that it's quite involved with all the unseen things you need to account and check for. Thus libraries like jQuery.

你会发现它完全涉及你需要考虑和检查的所有看不见的东西。因此像jQuery这样的库。

To convert the JSON string to a javascript object, use JSON.parse(). Here's the reference:

要将JSON字符串转换为javascript对象,请使用JSON.parse()。这是参考:

http://developer.mozilla.org/En/Using_native_JSON

Here's an example:

这是一个例子:

function readJSON(file) {
    var request = new XMLHttpRequest();
    request.open('GET', file, false);
    request.send(null);
    if (request.status == 200)
        return request.responseText;
};

var myObject = JSON.parse(readJSON('/local/path/to/json'));

EDIT #2: Thanks for editing in this example, Chase. A word of warning. It is not a good idea to make the open() method a synchronous call by using false in the 3rd parm. AJAX is intentionally designed for asynchronous use, and to make a synchronous call invites lock ups. As one who used to think there was a place for synchronous calls, I now find there's always a better way to get it done asynchronously. Word to the wise.

编辑#2:感谢在这个例子中编辑,Chase。一句警告。通过在第3个参数中使用false来使open()方法成为同步调用并不是一个好主意。 AJAX是专门为异步使用而设计的,并且使同步调用可以锁定。作为曾经认为有同步调用的地方的人,我现在发现总是有一种更好的方法来异步完成它。说到明智的话。

#2


1  

Please have a look at be below code snap which will on in all browsers, thanks

请看下面的代码快照,它将在所有浏览器中显示,谢谢

    function getJSONData(jsonurl) {
        var req = null;
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) { }
            }
        }
        req.open('GET', jsonurl, false);
        req.send(null);
        return req.status == 200 ? req.responseText : 'Error occurred';
    }
    var jsonData = JSON.parse(getJSONData('/local/path/to/json'));
    alert(getJSONData('/local/path/to/json'));

Hope this will be very helpful, thanks for your time

希望这对你的时间非常有帮助

#3


1  

I you're familiar with jQuery, this is a drop-in replacement for $.ajax:

我熟悉jQuery,这是$ .ajax的替代品:

Script:

function ajax( uri, settings ) {
    var ajax = new window.XMLHttpRequest(),
        data = settings.type == 'GET' ? '' : settings.data,
        async = settings.async ? settings.async : false;
        uri = settings.type == 'GET' ? uri + ( settings.data ? '?' + settings.data : '' ) : uri;

    ajax.onreadystatechange = function () {
        if ( ajax.readyState == 4 ) { //response ready
            if ( ajax.status == 200 ) { //success
                if ( settings.success ) settings.success( ajax.responseText, ajax.statusText );
                if ( settings.complete ) settings.complete( ajax, ajax.statusText );
            } else {
                if ( settings.error ) settings.error( ajax, ajax.status, ajax.statusText );
            };
        };
    };

    ajax.open( settings.type, uri, async );

    if ( settings.headers ) {
        for ( var header in settings.headers ) {
            ajax.setRequestHeader( header, settings.headers[header] );
        };
    };

    ajax.send( data );
};

Call it just like jQuery:

像jQuery一样调用它:

ajax( '/local/path/to/json', {
    "type": "GET", //or "POST"
    //"data": "<query string>", //if POST
    "success": function ( data, status ) {
        var myJson = window.JSON.parse( data );
    },
    "error": function ( response, status, error ) {
        // handle error
    }
} );