AJAX异步取缓存数据(先挖个坑,留着以后再用)

页面元素

 

<div id="loading"><img id="imgloading" src="/_layouts/CAResources/themeCA/images/loading.gif" alt="loading" /></div>
    <div id="PagIndex">
        <span id="Prev"> Prev  </span>
        <span id="Currentpage">1</span>
        <span id="Next">  Next </span>
    </div>

 

javascript

 

  ///通过AJAX得到数据
        function GetDataFromServer(pageIndex) { // by xu
            var ItemCode = $("#txtItemCode").val();
            var ItemDesc = $("#txtDesc").val();
            var PageType = ""; //E,C
            var ItemType = ""; //QO,PB......
            var isStore = 1;   //1?
            if ($("#<%= rbRequestType.ClientID%>").find("input[CHECKED]").val() == "Opex") {
                PageType = "E";
            }
            else {
                PageType = "C";
            }

            if ($("#<%= rbFormType.ClientID%>").find("input[CHECKED]").val() == "Store") {
                isStore = 1;
            }
            else {
                isStore = 0;
            }

            if ($("#<%= rbPRStorePurpose.ClientID%>").find("input[CHECKED]").val() == "Daily") {
                ItemType = "";
            }
            else if ($("#<%= rbPRStorePurpose.ClientID%>").find("input[CHECKED]").val() == "QuarterlyOrder") {
                ItemType = "QO";
            }
            else if ($("#<%= rbPRStorePurpose.ClientID%>").find("input[CHECKED]").val() == "PaperBag") {
                ItemType = "PB";
            }
            $.ajax({
                type: "Get",
                dataType: "json",
                url: "GetItemCode.aspx",
                data: { ItemCode: ItemCode, Desc: ItemDesc, ItemType: ItemType, sItemStart: PageType, pageIndex: pageIndex, isStore: isStore },
                beforeSend: function () {
                    //清除老数据。
                   
                    $("#loading").show();
                },
                success: function (jsonList) {
                    if (!jsonList) {
                        alert("There are no avaliable item data");
                    }
                    else {
                        ReadJSON(eval(jsonList));
                    }
                },
                error: function (message) {
                    alert("Loading item failed:" + message);
                },
                complete: function () {
                    $("#loading").hide();
                    $("#Currentpage").text(pageIndex);
                }

            });
        }

 //读取从服务器端返回的json并将数据拼成html格式。
    function ReadJSON(jsonList) { // by xu
        var ItemHTML = "";
        for (var i in jsonList.ItemCode) {
            var TRHTML = "<tr>";
            if (i % 2 == 0) {
                TRHTML = "<tr class='each-row'>";
            }
            else {
                TRHTML = "<tr class='ms-alternating'>";
            }
            TRHTML += CreateTD("TDData", jsonList.ItemCode[i]["Title"]);
            TRHTML += CreateTD("TDData", jsonList.ItemCode[i]["ItemType"]);
            TRHTML += CreateTD("TDData", jsonList.ItemCode[i]["Description"]);
            TRHTML += CreateTD("TDData", jsonList.ItemCode[i]["Unit"]);
            TRHTML += CreateTD("TDData", jsonList.ItemCode[i]["AssetClass"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["VendorID"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["DeliveryPeriod"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["UnitPrice"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["TaxValue"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["IsAccpetDecimal"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["Currency"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["ItemScope"]);
            TRHTML += CreateTD("hidden", jsonList.ItemCode[i]["PackagedRegulation"]);
            TRHTML += "</tr>";
            ItemHTML += TRHTML;

        }
        ClearItemData();
        $(ItemHTML).insertAfter("#TRTitle");
        SetPrveNextStatus(jsonList.TotalCount[0]["Count"]);
    }

  //设置下一页和上一页的显示状态
    function SetPrveNextStatus(totalCount) {
        if (CurrentPageIndex * PageSize < totalCount) {
            $("#Next").show();
        }
        else {
            $("#Next").hide();
        }

        if (CurrentPageIndex > 1) {
            $("#Prev").show();
        }
        else {
            $("#Prev").hide();
        }
       // alert("TotalCount:" + totalCount + "CurrentIndex:" + CurrentPageIndex);
    }

 

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using System.Data;
using System.Text;

namespace CA.WorkFlow.UI.PurchaseRequest
{
    public partial class GetItemCode :  System.Web.UI.Page//CAWorkFlowPage//
    {
        /// <summary>
        /// Itemcode缓存的Key
        /// </summary>
        internal string sItemCacheKey = "ItemCode";
        internal TimeSpan tsCache = TimeSpan.FromMinutes(PurchaseRequestCommon.GetPRCacheMinutes());

        int iPageSize = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string sItemCode = Context.Request.QueryString["ItemCode"].ToString();
                string sDecription = Context.Request.QueryString["Desc"].ToString();
                string sItemTyp = Context.Request.QueryString["ItemType"].ToString();// QO,PB......
                string sItemStart = Context.Request.QueryString["sItemStart"].ToString();//E,X
                string sIsStore = Context.Request.QueryString["isStore"].ToString();//
                int iPageIndex = int.Parse(Context.Request.QueryString["pageIndex"].ToString());
                string sJson = SearchItemCode(sItemCode, sDecription, sItemTyp, sItemStart, iPageIndex, sIsStore == "1" ? true : false);
               
                Response.Clear();
                Response.Write(sJson);
            }
            catch (Exception ex)
            {
                CommonUtil.logError("CA.WorkFlow.UI.PurchaseRequest.GetItemCode has an error:" + ex.ToString());
            }
            Response.End();
        }

        string SearchItemCode(string sItemCode, string sDecription, string sItemTyp, string sItemStart, int iPageIndex, bool isStore)
        {
            string sJson = string.Empty;
            DataTable dtResult = new DataTable();
            DataTable dt = new DataTable();
            dt = PurchaseRequestCommon.GetActiveItemCode();/得到所有的可用的ItemCode数据
            EnumerableRowCollection<DataRow> drColle = from dr in dt.AsEnumerable()
                                                       where (string.IsNullOrEmpty(sItemCode) || AsString(dr["Title"]).StartsWith(sItemCode, StringComparison.CurrentCultureIgnoreCase))
                                                       && (string.IsNullOrEmpty(sDecription) || AsString(dr["Description"]).Contains(sDecription))
                                                       && (isStore ? AsString(dr["ItemScope"]).Trim().Equals(sItemTyp, StringComparison.CurrentCultureIgnoreCase) : true) //QO,PB......
                                                       && (AsString(dr["Title"]).StartsWith(sItemStart, StringComparison.CurrentCultureIgnoreCase) || AsString(dr["Title"]).StartsWith("X", StringComparison.CurrentCultureIgnoreCase))//E,C
                                                       select dr;
            DataTable dt10 = drColle.CopyToDataTable();
            int iCount = dt10.Rows.Count;
            if (iCount > 0)
            {
                int iCurrentRow = (iPageIndex - 1) * iPageSize;

                List<DataRow> listDr = new List<DataRow>();

                int iMaxRowIndex = iCurrentRow + iPageSize;
                if (iCount < iPageSize)///当结果行数少于每页显示的行数
                {
                    iMaxRowIndex = iCount;
                }
                if (iMaxRowIndex > iCount)//请求的最后一页所要求的行数大于所在行数。
                {
                    iMaxRowIndex = iCount;
                }


                for (int i = iCurrentRow; i < iMaxRowIndex; i++)
                {
                    listDr.Add(dt10.Rows[i]);
                }
                dtResult = listDr.CopyToDataTable();
                sJson = PurchaseRequestCommon.DataTableToJson("ItemCode", dtResult, iCount);
            }
            return sJson;
        }


        /// <summary>
        /// 得到可用的ItemCode的数据(从缓存中读取。)
        /// </summary>
        /// <returns></returns>
        public DataTable GetActiveItemCode()
        {
            DataTable dt = new DataTable();
            dt = HttpContext.Current.Cache[sItemCacheKey] as DataTable;
            if (dt == null)///缓存过期或缓存中没有
            {
                SPQuery query = new SPQuery();
                query.Query = @"
                            <Where>
                                <Eq>
                                    <FieldRef Name='IsActive' />
                                    <Value Type='Boolean'>1</Value>
                                </Eq>
                            </Where>";
                ///query.RowLimit = 10;
                query.ViewFields = GetQueryFiled();
                dt = SPContext.Current.Web.Lists["Item Codes"].GetItems(query).GetDataTable();
                HttpContext.Current.Cache.Insert(sItemCacheKey, dt, null, System.Web.Caching.Cache.NoAbsoluteExpiration, tsCache);
            }
            return dt;
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        string GetQueryFiled()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<FieldRef Name='Title'/>");
            sb.Append("<FieldRef Name='ItemType'/>");
            sb.Append("<FieldRef Name='Description'/>");
            sb.Append("<FieldRef Name='Unit'/>");
            sb.Append("<FieldRef Name='AssetClass'/>");
            sb.Append("<FieldRef Name='VendorID'/>");
            sb.Append("<FieldRef Name='DeliveryPeriod'/>");
            sb.Append("<FieldRef Name='UnitPrice'/>");
            sb.Append("<FieldRef Name='TaxValue'/>");
            sb.Append("<FieldRef Name='IsAccpetDecimal'/>");
            sb.Append("<FieldRef Name='Currency'/>");
            sb.Append("<FieldRef Name='ItemScope'/>");
            sb.Append("<FieldRef Name='PackagedRegulation'/>");
            return sb.ToString();
        }


        string AsString(object o)
        {
            if (o == null)
            {
                return string.Empty;
            }
            else
            {
                return o.ToString();
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值