javascript 如何将 JSON 从本地 url 设置为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8191238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:36:40  来源:igfitidea点击:

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

javascriptjson

提问by Chase Florell

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.

回答by Jonathan M

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

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

http://developer.mozilla.org/en/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

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 falsein 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。一句警告。open()通过false在第三个参数中使用使方法成为同步调用并不是一个好主意。AJAX 是专门为异步使用而设计的,并且进行同步调用会导致锁定。作为曾经认为有一个地方可以进行同步调用的人,我现在发现总有一种更好的方法可以异步完成它。对智者说。

回答by ThinkingStiff

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

回答by Elias Hossain

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

希望这会很有帮助,感谢您的时间