【问题标题】:How to read JSON file with Dojo如何使用 Dojo 读取 JSON 文件
【发布时间】:2011-03-15 11:25:53
【问题描述】:

如何使用 Dojo 读取 JSOn 文件?

【问题讨论】:

    标签: dojo


    【解决方案1】:

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

    【讨论】:

    • 你没有关闭需求。您需要添加“);”在您的代码末尾。
    • 已修复!谢谢,劳伦斯。
    • 当我在 require 中提供文件名时,如何在 'dojo/text!/path/to/data.json' 中添加我的上下文路径?像这样:location.pathname.replace(/\/[^/]*$/, '')。
    • 当前级别访问“config”文件夹的示例:'dojo/text!./config/config.json
    【解决方案2】:

    这是一个有点宽泛的问题。

    如果你的意思是,你如何发出服务器请求并在返回的路上自动将其视为 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) 用于另一个方向)。

    【讨论】:

      【解决方案3】:

      使用道场 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
      
          });
      

      【讨论】:

        【解决方案4】:

        你可以使用 dojo/request 模块:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-21
          • 2017-12-23
          • 2022-12-12
          • 1970-01-01
          • 2017-10-03
          • 1970-01-01
          • 1970-01-01
          • 2018-10-20
          相关资源
          最近更新 更多