EXT 中jsonreader的配置解釋

來源:互聯網
上載者:User

JsonReader

在JavaScript中,JSON是一種非常重要的資料格式,key:value的形式比XML那種複雜的標籤結構更容易理解,代碼量也更小,很多人傾向於使用它作為EXT的資料交換格式。為Json- Reader準備的JSON資料如下面的代碼所示。

var data = {id:0,totalProperty:2,successProperty:true,root:[{id:'id1',name:'name1',descn:'descn1'},{id:'id2',name:'name2',descn:'descn2'}]};

與數組相比,JSON的最大優點就是支援分頁,我們可以使用totalProperty參數表示資料的總量。successProperty參數是可選的,可以用它判斷當前請求是否執行成功,進而判斷是否進行資料載入。在不希望JsonReader處理響應資料時,可以把successProperty設定成false。

現在來討論一下JsonReader,看看它是如何與上面的JSON資料對應的,如下面的代碼所示。

var reader = new Ext.data.JsonReader({successProperty: "successproperty",totalProperty: "totalProperty",root: "root",id: "id"}, [{name:'id',mapping:'id'},{name:'name',mapping:'name'},{name:'descn',mapping:'descn'}]);

上例中的對應方式不夠簡潔,因為name和mapping部分的內容是相同的,其實這裡的mapping可以省略,預設會用name參數從JSON中獲得對應的資料。如果不想與JSON裡的名字一樣,也可以使用mapping修改。不過,mapping在這裡還有其他用途,如代碼清單10-3所示。

代碼清單10-3 為JsonReader設定mapping進行資料對應

var data = {id:0,totalProperty:2,successProperty:true,root:[{id:'id1',name:'name1',descn:'descn1',person:{id:1,name:'man',sex:'male'}},{id:'id2',name:'name2',descn:'descn2',person:{id:2,name:'woman',sex:'female'}}]};var reader = new Ext.data.JsonReader({successProperty: "successproperty",totalProperty: "totalProperty",root: "root",id: "id"}, ['id','name','descn',{name:'person_name',mapping:'person.name'},{name:'person_sex',mapping:'person.sex'}]);

在上面的代碼中,我們使用JSON支援更複雜的嵌套結構,其中的person對象自身就擁有id、 name和sex等屬性。在JsonReader中可以用mapping把這些嵌套的內部屬性對應出來,賦予對應的record,而其他欄位都不變

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.