如何使用Dojo读取JSON文件

Dam*_*mir 9 dojo

如何用Dojo读取JSOn文件?

voi*_*ate 23

在Dojo 1.8+中,要加载JSON文件(而不是XHR),请使用dojo/text加载文件,然后使用dojo/json进行解析.像这样:

require( [ 'dojo/json', 'dojo/text!/path/to/data.json' ], 
    function( JSON, data )
{
    var data = JSON.parse( data );
} );
Run Code Online (Sandbox Code Playgroud)

不是"!" 在dojo/text之后,用于指定要加载的文件.


Ken*_*iro 14

这是一个广泛的问题.

如果你的意思是,你如何提出服务器请求并在回来的路上自动将其视为JSON,你可以这样做:

dojo.xhrGet({
    url: "your/server/endpoint/here",
    handleAs: "json",
    load: function(obj) {
        /* here, obj will already be a JS object deserialized from the JSON response */
    },
    error: function(err) {
        /* this will execute if the response couldn't be converted to a JS object,
           or if the request was unsuccessful altogether. */
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意handleAs: "json",它会告诉dojo.xhrGet(或xhrPost等)在触发load回调之前尝试将响应转换为JS对象.

http://dojotoolkit.org/reference-guide/dojo/xhrGet.html

单独地,如果您已经拥有一个JSON字符串并且只需要将其转换为JS对象,那么Dojo就是dojo.fromJson(str)为此(以及dojo.toJson(obj)另一个方向).