2012-02-27 23 views
-1

我想使用dojo消耗Restful web服務。 web服務的結果返回瀏覽器,但是當我嘗試使用XHR我總是得到一個空值獲得的結果,所以請幫助我在道場新...使用dojo消耗webservice

dojo.query("li").onclick(function(){ 
     var xhrArgs = { 
       url: "http://192.168.1.65:9080/RAD8JAX-RSWeb/jaxrs/customers", 

       handleAs: "json", 
       headers: { "Content-Type": "application/json"}, 
       load: function(data) { 
       alert("ok"); 
        console.log(data); 
       }, 
       error: function(error) { 
        console.log(error); 
       } 
      }; 
      dojo.xhrGet(xhrArgs); 
console.log("message sent ..."); 
}); 

當事件發生警報顯示,我得到「空」

+0

你在上http://192.168.1.65:9080使得從HTML頁面的請求? – abraham 2012-02-27 19:07:17

回答

2

Dojo使用'stores'從服務器獲取數據。這些商店會延遲並取出數據,所以只有當您第一次請求時纔會這樣。每當你的JavaScript代碼需要數據時,它可以詢問商店,如果它已經提取了它,它將返回它,否則它將會出去並獲取它。

由於商店的異步特性,每次需要數據時都需要進行異步調用。

在你的情況,你可以這樣做:

// Create the store for later use 
var store = new dojo.data.ItemFileReadStore({ 
    contentType: 'application/json' 
    ,clearOnClose: true 
    ,urlPreventCache: true 
    ,url: "http://192.168.1.65:9080/RAD8JAX-RSWeb/jaxrs/customers" 
}); 

每一次你需要從商店的數據,你做的時間:

store.fetch({ 
    onItem: function(item, request) { 
    alert('I fire after each returned json item') 
    } 
    ,onComplete: function(items, findResult) { 
    alert('I fire when the data has loaded completely.'); 
    } 
    ,onError: function(error, request) { 
    alert('I fire when an error occurs'); 
    } 
}); 

僅在第一次就會有請求發送到服務器。所有其他請求將從商店緩存中提供。如果你想刷新緩存,你需要'關閉'商店。下一次取會叫上店裏會導致新的請求server.You可以關閉它,像這樣:

store.close(); 

門店設計在數據技術TRANSPARANT方式服務的服務器數據。因此,無論您服務的是json,xml還是csv,它都將被加載到商店中並以相同的方式提供給您。你只需要知道兩件事情:

  1. 的數據需要以一定的格式送達:對格式
  2. 您在onItem和的onComplete方法得到的所有項目見http://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore#item-structure-examples只能通過使用dojo閱讀API,你可以在這裏閱讀:http://dojotoolkit.org/api/1.7/dojo/data/api/Read

有很多類型的商店,ItemFileReadStore只是一個例子。

希望這有助於

+0

非常感謝你我真的很喜歡你的幫助我試試這個 我想告訴你當我打電話給webservice時會產生的json [{「lastName」:「Ziosi」,「title」:「Mr」,「 firstName「:」Lara「,」ssn「:」888-88-8888 「}] 我該如何處理這個問題,它是一個jsonArray:/ – 2012-02-28 00:59:40

+0

這個數組是未命名的使用它是一個問題嗎? – 2012-02-28 01:30:58

+1

如果您閱讀http://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore#item-structure-examples,您會看到商店需要另一個json結構。您需要將數組封裝在如下結構中:{ 「identifier」:「id」, 「items:[{id:1. ... this item of this item ...},{Id:2, ...此項目的其他信息...},等 ] } – koenpeters 2012-02-28 07:54:24