2012-11-03 55 views
1

我對DOJO有一個要求。單元測試時,我使用了一個簡單的* .json文件,並且正如代碼所示,我正在調用一個簡單的xhr.get或request.get調用。DOJO ... dojo/_base/xhr vs dojo /請求API

然而,道場/請求失敗時,我使用的配置選項「handleAs:‘JSON’」來解析它接收到的JSON

這裏是「roles.data.json」文件的內容:

{roles:["Role - A", "Role - B", "Role - C", "Role - D", "Role - E"]} 

這裏是道場碼不起作用

require([ 
     'dojo/dom', 
     'dojo/on', 
     'dojo/ready', 
     'dojo/parser', 
     'dojo/request', 
     'dijit/registry', 
     'dijit/form/Form', 
     'dijit/form/TextBox', 
     'dijit/form/ValidationTextBox', 
     'dijit/form/ComboBox', 
     "dojo/domReady!" 
    ], function (dom, on, ready, parser, request, registry) { 
     ready(function() { 
      console.log("ready"); 
      request.get("http://localhost/dojofun/data/roles.data.json",  { 
       //offending piece of code here, if I remove this, request works as string     
       handleAs :'json', 
       //headers : { 'mime-type': 'application/json' } 
      }).then (function (data) { 
       try { 
        console.log(data) 
        //var d = eval(data); 
        console.log(data.roles[0]); 
       } 
       catch (err) { 
        console.log(err); 
       } 

      }); 

     }); 
    }); 

這裏是不工作的道場代碼。

require([ 
     'dojo/dom', 
     'dojo/on', 
     'dojo/ready', 
     'dojo/parser', 
     'dojo/_base/xhr', 
     'dijit/registry', 
     'dijit/form/Form', 
     'dijit/form/TextBox', 
     'dijit/form/ValidationTextBox', 
     'dijit/form/ComboBox', 
     "dojo/domReady!" 
    ], function (dom, on, ready, parser, xhr, registry) { 
     ready(function() { 
      console.log("ready"); 
      xhr.get({ 
       url:"http://localhost/dojofun/data/roles.data.json", 
       handleAs :'json', 
       load:function (data) { 
         try { 
          console.log(data) 
          console.log(data.roles[0]); 
         } 
         catch (err) { 
          console.log(err); 
         } 
        }  
      }); 

     }); 
    }); 

我的問題是,當我使用request.get時,我錯過了什麼?我需要額外進口嗎?

===============

好的!發現錯誤..這是愚蠢的,但你的JSON必須在雙引號....單引號導致語法錯誤。正確的JSON現在看起來是這樣的:

{"roles":["Role - A", "Role - B", "Role - C", "Role - D", "Role - E"]} 
+0

是否有在JavaScript控制檯中指出的任何錯誤?你可以添加一個錯誤回調到你的'.then()'並記錄任何錯誤對象嗎? – Leftium

+0

不,沒有錯誤....它似乎沒有進入 - >然後(函數(數據){}) – user478727

+0

沒有錯誤回調,你在xhr調用期間忽略任何錯誤:'then(function(數據){},函數(錯誤){console.log(錯誤)})' – Leftium

回答

0

好吧,我有兩個猜測:

  1. 你的JSON格式不正確。從技術上講,所有JSON字段名稱和字符串必須是:「雙引號」。
  2. 您是not sending the proper Content-Type: application/json header

In addition to the encoding the data as JSON in the response, set the Content-Type header to application/json, either using server configuration such as Apache's AddType or adding it to the header with the server side code.


我想這是#1