ExtJS入門教程05,grid的異步加載數據


上一篇演示了extjs grid的基本用法,並加載了本地數據。今天我們將演示如何加載異步數據。

所謂異步,就是通過ajax的方式將服務器端的數據加載到我們的grid中。為了提供數據,我們先定義一個數據類,並創建一些臨時數據。

public class UserEntity
{
    public string ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public static List<UserEntity> UserList = null;
    static UserEntity()
    {
        UserList = new List<UserEntity>();
        UserList.Add(new UserEntity() { ID = "1", Name = "齊飛1", Age = 27 });
        UserList.Add(new UserEntity() { ID = "2", Name = "齊飛2", Age = 27 });
        UserList.Add(new UserEntity() { ID = "3", Name = "齊飛3", Age = 27 });
        UserList.Add(new UserEntity() { ID = "4", Name = "齊飛4", Age = 27 });
        UserList.Add(new UserEntity() { ID = "5", Name = "齊飛5", Age = 27 });
        UserList.Add(new UserEntity() { ID = "6", Name = "齊飛6", Age = 27 });
    }
}

有了數據,我們來創建一個HttpHandler,我們通過handler來提供數據:

public class gridAsync : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/json";
        Common.HandleResult result = new Common.HandleResult();
        result.Set(true, Entity.UserEntity.UserList);
        string jsonString = JsonConvert.SerializeObject(result);
        context.Response.Write(jsonString);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

我們這里使用了Json.net來將數據序列化為json字符串。

然后,我們來改造一下上一篇的代碼。上一篇中已經提到過,grid中的數據都是通過store來提供的,當我們修改了數據獲取方式以后,我們只需要修改store的定義即可。

var myStore = Ext.create('Ext.data.Store', {
    model: 'User',
    autoLoad: true,
    proxy: {
        type: "ajax",
        url: "/handlers/gridAsync.ashx",
        reader: {
            type: 'json',
            root: "data",
            idProperty: 'ID'
        }
    }
});

首先,添加了autoLoad屬性,這個屬性表示自動加載url中的數據。

然后的proxy屬性,這是一個數據代理,extjs中有很多數據代理,具體可以分為服務器端代理和客戶端代理,關於代理的文章我之前也下過兩篇,感興趣的小伙伴可以去看看:

  • ExtJS 4.2 客戶端代理(proxy)
  • ExtJS 4.2 服務器代理(proxy)

proxy中的url屬性就是我們剛才定義的handler的地址。

完成改造以后,運行我們的程序,一個簡單的異步加載的grid就完成了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM