2011-03-15 70 views

回答

13

这是一个广泛的问题。

如果你的意思是,你如何让一个服务器请求,并让作为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.fromJson(str)这个(和dojo.toJson(obj)为其他方向)。

+0

+1一个非常完整的答案。 – 2011-03-15 12:31:57

1

随着道场1.8: 模块ID “道场/请求/ 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 

    }); 
21

在道场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之后,用于指定要加载的文件。

+0

您没有关闭要求。你需要添加“);”在代码的最后。 – Laurence 2012-10-24 11:40:39

+0

固定!谢谢,劳伦斯。 – voidstate 2013-12-05 16:37:43

+0

当我在require中指定文件名时,如何在'dojo/text!/path/to/data.json'中添加我的上下文路径?像这样:location.pathname.replace(/ \/[^ /] * $ /,'')。 – coder247 2016-03-26 09:23:36

0

您可以使用Dojo /请求模块:

<script> 
    require(["dojo/request", function(request){ 
     request("patho/to/file.json" , {handleAs :"json"}).then(function(result){/*success*/} , function(err){/*Oops!*/}) 

    }); 
</script>