【发布时间】:2011-03-15 11:25:53
【问题描述】:
如何使用 Dojo 读取 JSOn 文件?
【问题讨论】:
标签: dojo
如何使用 Dojo 读取 JSOn 文件?
【问题讨论】:
标签: dojo
在 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 );
} );
不是“!”在dojo/text之后,用于指定要加载的文件。
【讨论】:
'dojo/text!./config/config.json
这是一个有点宽泛的问题。
如果你的意思是,你如何发出服务器请求并在返回的路上自动将其视为 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. */
}
});
注意上面的handleAs: "json",它告诉dojo.xhrGet(或xhrPost等)在触发load回调之前尝试将响应转换为JS对象。
http://dojotoolkit.org/reference-guide/dojo/xhrGet.html
单独来说,如果您已经有自己的 JSON 字符串并且只需要将其转换为 JS 对象,Dojo 有dojo.fromJson(str) 用于此(而dojo.toJson(obj) 用于另一个方向)。
【讨论】:
使用道场 1.8: 将模块 ID“dojo/request/xhr”添加到您的依赖项和 xhr 作为回调参数,然后:
xhr("path/to/file.json", {
handleAs: "json"
}).then(function(obj){
// do something with the obj
}, function(err){
// Handle the error condition
}, function(evt){
// Handle a progress event from the request if the
// browser supports XHR2
});
【讨论】:
你可以使用 dojo/request 模块:
<script>
require(["dojo/request", function(request){
request("patho/to/file.json" , {handleAs :"json"}).then(function(result){/*success*/} , function(err){/*Oops!*/})
});
</script>
【讨论】: